Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django detailview in bootstrap modal
How i can get detail view in bootstrap5 modal? (Without jquery please). Modal opens from link(no from button). -
Django: create groups with permissions
I'm trying to create a UserRank model that have a field called group, group is related to a specific group with permissions. The Code models.py: # Create your models here. class UserRank(models.Model): rank_name= models.CharField(max_length=50, unique=True) group = models.OneToOneField(Group, blank=True, null=True, on_delete=models.SET_NULL) singals.py: @receiver(post_migrate) def create_rank_group(sender, **kwargs): # Create UserRank objects boss_rank, _ = UserRank.objects.get_or_create(role_name='boss') first_hand_role, _ = UserRank.objects.get_or_create(role_name='first hand') # Create Group objects for each UserRank boss_group, _ = Group.objects.get_or_create(name='boss') first_hand_group, _ = Group.objects.get_or_create(name='first hand') # Assign permissions to each Group boss_permissions = Permission.objects.filter(codename__in=['add_user','delete_user',]) first_hand_permissions = Permission.objects.filter(codename__in=['add_place', 'delete_place',]) # Set (connect) the permissions to each Group boss_group.permissions.set(boss_permissions) first_hand_group.permissions.set(first_hand_permissions) # Assign each Group to the appropriate UserRank boss_rank.group.set(boss_group) first_hand_role.group.set(first_hand_group) The Problem The error I got when I run the code: boss_role.group.set(boss_group) ^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'set' -
Why is this template not rendering when I have cripsy forms installed?
I'm having trouble rendering a template for a signup.html page in django. The error consists of: TemplateDoesNotExist at /accounts/create/ Error during template rendering In template [PATH_NAME]\cryptoProj\backend\templates\signup.html, error at line 21 bootstrap4/uni_form.html Line 21 is: <p>{{ form | crispy }}</p> The full file is: {% load static %} {% load crispy_forms_tags %} {% block metadescription %} Sign up to get a new account with us. The perfect solution to buy and sell your Cryptocurrencies. {% endblock %} {% block title %} Create a New Account - Crypto Dashboard {% endblock %} {% block content %} <div> {% if not form.is_valid %} <div class="mx-auto"> <br> <h1 class="my_title text-center">Create a new account</h1> <br> <div class="col-9 col-sm-9 col-md-6 col-lg-5 mx-auto bg-light"> <br> <p>Enter the following information to create a new account.</p> <form method="post"> <p>{{ form | crispy }}</p> {% csrf_token %} <button type="submit" class="btn btn-secondary">Register Account</button> </form> <br> </div> </div> {% else %} <div class="mx-auto"> <br> <h1 class="my_title text-center">Your account has been successfully created</h1> <br> <div> <p> Dear Customer, <br> <br> Your account has been created and it is ready to use. <br> </p> </div> </div> {% endif %} </div> <br> {% endblock %} I have crispy forms pip installed and added to installed_apps … -
Celery worker not handling streaming data properly
I am running a streaming task inside a celery worker which is giving me 1 minute candle stick data and then I'm converting that 1 minute incoming data to 5 minute data but this task always starts giving some wierd output after sometime but works fine when I run it on jupyter notebook separately. df = pd.DataFrame(columns=['time', 'open', 'high','low','close']) df.set_index('time', inplace=True) cache.set('df', df) df_5min=pd.DataFrame() cache.set('df_5min',df_5min) max_strategy_run=2 cache.set('max_strategy_run', max_strategy_run) @shared_task(name="strategy_1",queue='strategy_1_queue') def strategy_1(): client = easy_client( api_key='', redirect_uri='', token_path='') stream_client = StreamClient(client) strategy=Strategy.objects.filter(name="strategy_1").first() stock_symbol=strategy.stock.symbol async def read_stream(): await stream_client.login() await stream_client.quality_of_service(StreamClient.QOSLevel.FAST) async def print_message(message): #global df #global df_5min #global max_strategy_run #global place_order_data if message['service']=='CHART_EQUITY': df=cache.get('df') df_5min=cache.get('df_5min') max_strategy_run=cache.get('max_strategy_run') if max_strategy_run==0: await stream_client.chart_equity_unsubs([stock_symbol]) await stream_client.level_one_equity_unsubs([stock_symbol]) if df.shape[0]==0 and datetime.datetime.fromtimestamp(message['content'][0]['CHART_TIME']/1000).minute%5!=0: pass else: df = df.append({ 'time': datetime.datetime.fromtimestamp(message['content'][0]['CHART_TIME']/1000), 'open': message['content'][0]['OPEN_PRICE'], 'high': message['content'][0]['HIGH_PRICE'], 'low': message['content'][0]['LOW_PRICE'], 'close': message['content'][0]['CLOSE_PRICE'], },ignore_index=True) print(json.dumps(message, indent=4)) if df.shape[0]==5: df.set_index('time', inplace=True) df = df.resample('5T').agg({'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last'}) df_5min=copy.deepcopy(df) print('New DataFrame (5 minute):\n', df_5min) if df_5min.loc[df_5min.index[0],'open']>df_5min.loc[df_5min.index[0],'close']: max_strategy_run=max_strategy_run-1 option=await getOptionSymbol(client,message['content'][0]['key']) print(option) place_order_data = await placeOrderDataStrategy1(option,df_5min) print(place_order_data) df.drop(index=df.index, inplace=True) await stream_client.chart_equity_unsubs([stock_symbol]) await stream_client.level_one_equity_subs([stock_symbol]) else: df.drop(index=df.index, inplace=True) cache.set('df',df) cache.set('df_5min',df_5min) cache.set('max_strategy_run', max_strategy_run) elif message['service']=='QUOTE': df=cache.get('df') max_strategy_run=cache.get('max_strategy_run') df_5min=cache.get('df_5min') print(message)w if max_strategy_run==0: message['content'][0]['LAST_PRICE']=12345678 if ((datetime.datetime.now() - df_5min.index[0]).total_seconds() / 60)<20: try: if message['content'][0]['LAST_PRICE']<df_5min.loc[df_5min.index[0],'low']: # here we'll place order … -
FactoryBoy related factory objects not available in post_generation
I have a factory for a Django model (Questionnaire) where I create a set of related items in a trait (Questions that have a foreign key pointing to the Questionnaire). The Questionnaire also has a many-to-many field pointing to a Dimension model. The factory, optionally, adds a set of Dimension objects to the Questionnaire in a post_generation method. Now, if questions have been added, I want to set the dimension field on each of them to a random choice from these dimensions. This is what I have: class QuestionnaireFactory(DjangoModelFactory): class Meta: model = models.Questionnaire class Params: with_questions = Trait( questions=RelatedFactoryList( QuestionFactory, "questionnaire", size=3, with_choices=True, ) ) # Add dimensions to the questionnaire. @factory.post_generation def dimensions(self, create, extracted, **kwargs): # First add the dimensions to the questionnaire. if create and extracted: self.dimensions.add(*extracted) # What I want to do: Add random dimension to each question (doesn't work) for question in self.question_set.all(): question.dimension = Faker("random_element", elements=extracted) question.save() Which I would call with: dimensions = factories.DimensionFactory.create_batch(3) questionnaire = factories.QuestionnaireFactory.create(with_questions=True, dimensions=dimensions) However, self.question_set.all() is empty in the post_generation hook. So, with the code as above, the dimension field is not being set on any question. It appears that the creation of the questions is happening … -
Django: maximum recursion depth exceeded in comparison - Postman works
I have a Django backend running as a service on an Ubuntu machine. After a while, I am getting this error when trying to execute my requests: maximum recursion depth exceeded in comparison I have attached to the process and found where the problem is occurring: response = requests.delete( apiUrlAddEntries, verify=False ) return response The debugger does not get inside the Delete call, it just trigger that exception. However, if I send the same delete call using Postman (on the same machine, toward the same server), all goes through fine. What do you think? Is it because the request lib? What cold make it run from Postman side and not from the request lib call? If I restart the service, it goes fine, for a while that is. -
ModuleNotFoundError: No module named 'apscheduler.schedulers'; 'apscheduler' is not a package
ModuleNotFoundError: No module named 'apscheduler.schedulers'; 'apscheduler' is not a package Errors like this occur. I have already installed the apscheduler library. Version used: python3.11.0 Framework in use: Django from apscheduler.schedulers.background import BackgroundScheduler from datetime import datetime, timedelta import pytz import requests import json from .models import Todo def notify_todo(): #現在の時刻を取得 now = datetime.now(pytz.timezone('Asia/Tokyo')) #締切が24時間以内のTODOリストを取得 todos = Todo.objects.filter(deadline__range=(now, now + timedelta(days=1))) for todo in todos: #LINE NotifyのAPIトークンを取得 api_token = 'xxxxxxxxxxxxxxxxxxxx' #通知メッセージの作成 message = f"【{todo.title}】\n締切時間:{todo.deadline.strftime('%Y/%m/%d %H:%M')}\n詳細:{todo.description}" #LINE Notifyに通知を送信 headers = {'Authorization': f'Bearer {api_token}'} payload = {'message': message} requests.post('xxxxxxxxxxxxxxxxxxxxxxx', headers=headers, data=payload) #BackgroundSchedulerの設定 scheduler = BackgroundScheduler(timezone='Asia/Tokyo') scheduler.add_job(notify_todo, 'interval', minutes=10)#10分ごとに実行 scheduler.start() -
How to create a DDOS protection for a webpage inside of the views
So recenty I have been working on a Django app for a school project, and some friends decided it would be funny to DDOS my webpage. I am currently looking for new friends and a way to protect against this. I am currently trying to use a decorator limits from the library. It does block when getting ddos attacked but the problem is it shuts down the whole website, giving the error RateLimitException, which i do not want, for obvious reasons. I want the program to be able to block that specific ip address sending the requests, how could i do this. Here is the imports in views with only the homepage. import ratelimit from ratelimit import limits @limits(calls=5, period=10) def home_page(request): request.session.get("user_id") if request.session.get('user_id') is not None: authorized=True return render(request,template_name="index.html",context={"authorize":authorized}) else: return render(request,template_name="index.html") . . . . . . . . . . . . -
One model for many views in django
Have a nice day! I just started to learn django framework and faced such problem. I'm making a small site where only one model is required, but this model is used to create pages through a slug, for example: domain.com/city/services domain.com/city/services/service-detail domain.com/city/services/service-detail-2 variables on the page change depending on the value of the slug "city". In all django tutorials, the class in the model is strongly associated with the target template. # appname/models.py from django.db import models from django.urls import reverse class City(models.Model): city = models.CharField(max_length=200, unique=True, db_index=True, verbose_name="Город на англ") slug = models.SlugField(max_length=200, unique=True, db_index=True, verbose_name="URL") phone1 = models.CharField(max_length=100, verbose_name="Основной телефон") gorod = models.CharField(max_length=200, verbose_name="Город") region = models.CharField(max_length=200, verbose_name="Область") def __str__(self): return self.gorod def get_absolute_url(self): return reverse('index', kwargs={'slug': self.slug}) In the view, too, binding to the model and a specific template # appname/views.py from django.views.generic import DetailView from .models import City class CityDetailView(DetailView): model = City template_name = 'index.html' And this is my URLS.py from django.urls import path from .views import CityDetailView urlpatterns = [ path('<slug:slug>', CityDetailView.as_view(), name='index'), ] How can I write a model so that I can use values in all templates dependent on the slug "city"? In laravel, I didn't use the database at all. To … -
Adding tasks to crontab does not work in docker container for image python:3.9.16-slim
I'm creating a container for a Django website. I need a dump DB every two weeks and sent to Google mail as a backup. To do this, I want to add two tasks to the crontab in the container where Django works, one will create a database dump, the other will archive it and send it to the mail. But I faced with a problem. I wrote the following in the Dockerfile: RUN apt update && apt install -y cron # Copy crontab2.txt file to the cron.d directory COPY crontab2.txt /etc/cron.d/new_cron # Give execution rights on the cron job RUN chmod 0644 /etc/cron.d/new_cron # Apply cron job RUN crontab /etc/cron.d/new_cron # Create the log file to be able to run tail RUN touch /var/log/cron.log # Run the command on container startup CMD ["cron", "-f"] In the process of creating the container, I received the following log: Step 4/27 : RUN apt update && apt install -y cron ---> Running in 715c47ebdac4 ... The following NEW packages will be installed: ... cron ... Get:2 http://deb.debian.org/debian bullseye/main amd64 cron amd64 3.0pl1-137 [99.6 kB] ... Selecting previously unselected package cron. Preparing to unpack .../1-cron_3.0pl1-137_amd64.deb ... Unpacking cron (3.0pl1-137) ... ... Setting up cron … -
I’m on my first ever django-python web project. CSS is messing up a lot
The html code: <div class=“main”> <img src={% static path/to/my/image %} alt=“image1” class=“second-image”> <div class=“about”> <h3>Dummy text</h3> <p>Lorem ipsum dolor sit amet</p> <button class=“btn”>Learn More</button> </div> </div> The media query I gave is (@media (max-width: 600px) I’m not copy-pasting my code as I’m typing this up on my phone. It’s also my first time in here. I’ve been trying way too many methods and got mixed up with what I wanted. Anyway, I built this webpage that’s looking good and working fine. I didn’t add any media queries and hence it isn’t responsive. What I’m trying to do now is to get the text to the bottom of the viewport and the image, placed left to the text, to the top. It’s something subtle but I can’t get it out. In case any of this is unclear, what I want is a smooth responsive page where the image gets displayed right after the text. I don’t think I can keep going if the first step is not going right. I don’t get how positioning works. Also, this part of the code comes after the hero section with those fancy picture and navigation bar and all that. When I tried different methods, … -
How do I get my background image to fit exactly within its responsive container - i.e. NOT keeping its aspect ratio?
All questions I come across talk about keeping an image's aspect ratio. I don't want the image to keep its aspect ratio. I want the image's width to exactly match the container's width, and the image's height to exactly match the container's height. The container is responsive. None of the settings I have tried solve this problem. Assuming my image is originally square and the responsive container is a horizontal rectangle: background-size: cover; This fills the container horizontally but keeps the aspect ratio, so it doesn't squash the image to fit completely within the container. background-size: contain; This fills the container vertically but repeats the image to fill it horizontally. It does not stretch the image horizontally to fill the container. Auto, inherit, unset, etc. are all just variations of keeping the aspect ratio. How can I make it so that my image dimensions match exactly the responsive container dimensions? My website project is only using DJango, CSS, HTML. -
Why does iterating over CheckboxSelectMultiple render bound method?
I am trying to iterate over a MultipleChoiceField with it's widget set as CheckboxSelectMultiple. I'm following the documentation specified here, which clearly states that I should be able to use {{ foo.tag }} to render the input element, however when I try, it renders this: <bound method BoundWidget.tag of <django.forms.boundfield.BoundWidget object at 0x7fbce1e38fd0>> It renders {{ foo.choice_label }} correctly. I have tried setting up a test project with roughly the same layout as below to test if this also happens in other projects, but there it rendered properly. I also tried to swap the widget to RadioSelect, which the documentation uses, but this also did not render properly. I use jinja2 as the template engine. forms.py: class GivePermissionsForm(forms.Form): def __init__(self, id, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["users"] = forms.MultipleChoiceField( choices=get_users(id), widget=forms.CheckboxSelectMultiple() ) users = forms.MultipleChoiceField() Note: get_users(id) is a method that returns a list of tuples in the format (user_id, user_name) views.py: def overview(request, id): # other, nonrelevant code form = GivePermissionForm(id) return render(reqest, "myapp/overview.jinja", {"form": form}) Note: overview.jinja2 includes form.jinja2. form.jinja2: <form> {% for user in form.users %} <label for="{{ user.id_for_label }}">{{ user.choice_label }}</label> {{ user.tag }} {% endfor %} </form> I also tried to set choices in CheckboxSelectMultiple, but … -
Docker doesn't see .env in dockerfile when trying to run Django collectstatic
I have multiple containers run in the order stated in docker-compose. In an app container, I need to execute file collectstatic. The thing is when I try to do it in dockerfile like that: RUN python manage.py collectstatic it breaks down as it doesn't see env vars, although the file is declared in the docker-compose. When I omit that line (and lines in other containers that depend on it) and I log into the container and generate the files - everything runs smoothly. How can I run it automatically? -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 29: invalid continuation byte
File "C:\Users\binc2\AppData\Roaming\Python\Python311\site-packages\keras\saving\saving_api.py", line 212, in load_model return legacy_sm_saving_lib.load_model( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\binc2\AppData\Roaming\Python\Python311\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler raise e.with_traceback(filtered_tb) from None File "C:\Users\binc2\AppData\Roaming\Python\Python311\site-packages\tensorflow\python\lib\io\file_io.py", line 703, in is_directory_v2 return _pywrap_file_io.IsDirectory(compat.path_to_bytes(path)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe1 in position 29: invalid continuation byte help me please, i don't know why this error occurs! -
not using django auth.login_required decorator will throw a TypeError of adding different data type fields together.Why?
Hello I have figured out the solution for my problem but I want to know why isit occuring in the first place. I am a beginner in django. I am buidling a social media website which has a function for handling likes on a post everything is working fine now. I figured the following error occured when i did not use login_required decorator it would throw error Tried to update field core.LikePost.post_id with a model instance, <Post: jay>. Use a value compatible with CharField. @login_required(login_url="signin") def like_post(request): username = request.user.username post_id = request.GET.get('post_id') post = Post.objects.get(id=post_id) like_filter = LikePost.objects.filter(post_id=post_id,username=username).first() if like_filter == None: new_like = LikePost.objects.create(post_id=post,username=username) new_like.save() post.no_of_likes = post.no_of_likes + 1 post.save() return redirect('/') else: like_filter.delete() post.no_of_likes = post.no_of_likes-1 post.save() return redirect("/") Models.py class Post(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4) user = models.CharField(max_length=100) image = models.ImageField(upload_to="post_images") caption = models.TextField() created_at = models.DateTimeField(default=datetime.now) no_of_likes = models.IntegerField(default=0) def __str__(self): return self.user class LikePost(models.Model): post_id = models.CharField(max_length=500) username = models.CharField(max_length=100) def __str__(self): return self.username I receive the error when i remove the login_required decorator.I just want to know why is this happening. Can somebody please explain why is this happening? -
pymongo.errors.OperationFailure: namespace name generated from index name is too long
I know the index name is too long, django_content_type_app_label_model_76bd3d3b_uniq, but this is auto genarate by django makemigrations, so how to edit and contral this long index name? TKS! pymongo.errors.OperationFailure: namespace name generated from index name is too long, full error: {'ok': 0.0, 'code': 67, 'errmsg': 'namespace name generated from index name is too long', 'operationTime': Timestamp(1677686036, 1)} The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/ec2-user/miniconda3/envs/py38/lib/python3.8/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/home/ec2-user/miniconda3/envs/py38/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/home/ec2-user/miniconda3/envs/py38/lib/python3.8/site-packages/djongo/sql2mongo/query.py", line 869, in parse raise exe from e djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: ALTER TABLE "django_content_type" ADD CONSTRAINT "django_content_type_app_label_model_76bd3d3b_uniq" UNIQUE ("app_label", "model") Params: () Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/ec2-user/miniconda3/envs/py38/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/home/ec2-user/miniconda3/envs/py38/lib/python3.8/site-packages/djongo/cursor.py", line 59, in execute raise db_exe from e djongo.database.DatabaseError -
Getting access token from vk.com. Django
The bottom line is this: make a so-called VK binding in order to obtain an access token. I'm trying to make a request, an error is thrown: { "error": "invalid_client", "error_description": "client_id is undefined" } I also first tried to authorize via VK, thinking that I could get an access token this way (I don’t know if it’s possible so really get it), and I sort of managed to implement authorization, and there were no errors about client_id. The question is: Is the idea of obtaining an access token correct (meaning, is it really done the way I intended, or is everything fundamentally wrong)? If not, how can it be implemented, if so, where are the errors? Code below views.py redirect to vk @login_required def vk_link(request): return redirect('https://oauth.vk.com/access_token/', params={ 'client_id': 'id', 'client_secret': 'token', 'redirect_url': 'http://127.0.0.1:8000/profile', 'code': request.GET.get('code'), }) urls.py urlpatterns = [ re_path(r'^login', views.login, name="login"), path('admin/', admin.site.urls), path('', views.index, name="main"), path('signUp', views.signUp, name="signUp"), path('profile', views.profile, name='profile'), path('logout', views.logout_view, name='logout'), path('vk', views.vk_link, name="vk"), ] **redirect button** <a href="{% url 'vk' %}"> <img src="" alt="vk"> </a> id and secret replaced for obvious reasons -
How to set WordPress to sub directory with Python(Django) project in nginx?
I want to set WordPress to the sub directory of the server that uses the root directory in the Python(Django) project. sample.com/ -> for Python(Django) project sample.com/wordpress -> for wordpress project The nginx configuration file is set as bellow, but if I access the URL sample.com/wordpress that I want to show WordPress, it will show 404 Not Found. How should I make the nginx configuration file in this case? server { listen 443 ssl default_server; server_name sample.com; ssl on; ssl_certificate /etc/letsencrypt/live/sample.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/sample.com/privkey.pem; location =/fabicon.ico {access_log off; log_not_found off;} location /static{ alias /usr/share/nginx/html/static; } location /media{ alias /usr/share/nginx/html/media; } location /{ include proxy_params; proxy_pass http://unix:/home/user/project/project/project.sock; } location /wordpress { alias /var/www/wordpress; index index.php; try_files $uri $uri/ /wordpress/index.php?q=$uri&$args; } location ~ ^/wordpress/.+\.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; } } -
Python3.9 Django Web API FrameWork Models - join Tables and convert to API
I have two tables, table A & table B, table A is managed = 'true' and table B is false. table A data from user input and table B data is from JIRA, table B will have more records compared to table A. I'm loading table B data from csv using load mysql statement. I converted table A to API and table B to API using Django rest framework. but I need table A + Table B data to covert it into API so that I can produce the results in web. Below is the sample model definition which I have. class modelA(models.Model): id=models.CharField(max_length=100, primary_key=True) type=models.CharField(max_length=100, null=True) comments=models.CharField(max_length=100, null=True) class modelB(models.Model): id=models.CharField(max_length=100, primary_key=True) status=models.CharField(max_length=100, null=True) duedate=models.DateField(null=True) I want left join modelA with modelB, and display all the data based on id column and convert it to API using Django Web Framework. I don't know how to do this, I googled and got many examples which specifies foreign key in model without primary key, and cascade delete option, but I don't want to delete anything and as I mentioned modelB is not managed by Django, could someone please suggest some simple steps to achieve this?, Thank You!! python 3.9, Distribution Redhat … -
How to Use Socket.io to send Messages from Django views.py?
so i am a bit new to this OK, so when i do it from outside the views.py it works perfectly and it console.logs in my browser running django my socketio_server.py file in the Django project folder import socketio import eventlet.wsgi # create a Socket.IO server sio = socketio.Server(cors_allowed_origins='*') # wrap with a WSGI application app = socketio.WSGIApp(sio) @sio.event def connect(sid, environ): print('Client connected:', sid) # start the server and listen for connections if __name__ == '__main__': eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 8080)), app) I then run this file using python3 socketio_server.py in the terminal python3 socketio_server.py (325591) wsgi starting up on http://0.0.0.0:8080 my JS file const socket = io('http://localhost:8080'); socket.on('connect', () => { console.log('Socket connected'); }); // # The below message needs to come from django views, but i get no such message in the console output socket.on('django', (data) => { console.log(data); }); so in the above js file i get the console.log of socket.on (connect) but not the below message which comes from the views my views.py file from practice.socketio_server import sio # Create your views here. def socket_testing(request): sio.emit("django","THIS MESSAGE IS FROM DJANGO VIEWS") print("I GOT THE MESSAGE") return render(request, 'testing/socket_testing.html') i run my python3 manage.py runserver 0.0.0.0:9000 and the python3 … -
How to implement a multi form 'wizard' using forms
I'm not using django-formtools, just built in forms. I'm struggling to understand the correct flow to construct such a view. I was trying to chain my logic like so def step_one(request, ...): if request.method == 'POST': form = step_one_form(data=request.POST) else: form = step_one_form() if form.is_valid(): foo = request.POST.get('foo') return step_two(request,foo) return render(request, 'wizard.html', context={'form',form}) def step_two(request, ...) if request.method == 'POST': form = step_two_form(data=request.POST) else: form = step_two_form() if form.is_valid(): foo = request.POST.get('foo') bar = request.POST.get('bar') return step_three(request, foo, bar) return render(request, 'wizard.html', context={'form',form} def get_view(request): return step_one(request) Edit: I realized that I can past data=request.POST to my form constructor, and that kind of works, but because step_two etc are always POST the form always shows "this field is required" errors on the first rendering. What is the preferred technique to not render the error on first load? Do you have to use a hidden field or something? -
How can I refer a field from a table which is not related with the field directly?
I am always confused by Django ORM especially joining tables, I think I am weak at it. I tried to JOIN 4 tables, Order, OrderDetail, Item and ItemPhoto and access to ItemPhoto.photo from Order table. However, I do not know what to do. Please let me ask you some good way to JOIN my tables. Thank you. PS. Maybe, my database schema is not good??? First Approach (without thinking deeply): # Error occured because Order table doesn't have item Field. subqs = ItemPhoto.objects.filter(item=OuterRef('item')).filter(priority=1) queryset = Order.objects.prefetch_related( Prefetch( 'orderdetail_orderid', queryset=OrderDetail.objects.select_related('order', 'item'), to_attr='oor', ), ).filter(user=user).order_by('-order').annotate( item_photos=Subquery(subqs.values('photo')), ) # FieldError: Cannot resolve keyword 'item' into field. Choices are: created_at, id, orderdetail_orderid, total_price, user, ... Second approach: # I read Manual and followed a way I found in it. # But, in this case, OuterRef(OuterRef('item')) means User.item??? subqs = ItemPhoto.objects.filter(item=OuterRef(OuterRef('item'))).filter(priority=1) # ◆ Changed ◆ queryset = Order.objects.prefetch_related( Prefetch( 'orderdetail_orderid', queryset=OrderDetail.objects.select_related('order', 'item'), to_attr='oor', ), ).filter(user=user).order_by('-order').annotate( item_photos=Subquery(subqs.values('photo')), ) # ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. Third Approach: queryset = Order.objects.prefetch_related( Prefetch( 'orderdetail_orderid', queryset=OrderDetail.objects.select_related('order', 'item').prefetch_related('item_photo'), # ◆ Changed ◆ to_attr='oor', ), ).filter(user=user).order_by('-order') # ◆ Changed ◆ # AttributeError: Cannot find 'item_photo' on OrderDetail object, 'item_photo' … -
What does mean from the Django Framework
If you want to change the server’s IP, pass it along with the port. For example, to listen on all available public IPs (which is useful if you are running Vagrant or want to show off your work on other computers on the network), use: python manage.py runserver 0.0.0.0:8000 What does it mean by listen on all available public IPs? I just want to know what it means -
django prefetch_related filtered with object column
models: class Person(models.Model): birth_date = models.DateField() class PersonData(models.Model): (...) last_name = models.CharField(max_length=255) valid_from = models.DateField() #default data urodzenia (Person) valid_to = models.DateField(default=date(year=2999,month=12,day=31)) class Transaction(models.Model): person = models.ForeignKey(Person, on_delete=models.RESTRICT) (...) And now I want to get transaction which are before context_date: context={} context[context_date]=date.today() transactions = Transaction.objects.filter(execution_date__lte=context['context_date']).prefetch_related.prefetch_related(Prefetch('person__persondata_set',queryset=PersonData.objects.filter(valid_to__gte=context['context_date'],valid_from__lte=context['context_date']))) But this is inproper - because the prefetch data uses in global context_date. I want to have name relevant to transaction.execution_date not context_date! Transaction.objects.filter(execution_date__lte=context['context_date']).prefetch_related.prefetch_related(Prefetch('person__persondata_set',queryset=PersonData.objects.filter(valid_to__gte=execution_date,valid_from__lte=execution_date)))