Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker and POSTGRESQL
I create new project using Docker on Django. when I write settings to connect to Postgres it has some Error - (conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "db" to address: nodename nor servname provided, or not known) Thats my code in project : settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432 } } docker-compose.yml version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db db: image: postgres:11 environment: POSTGRES_DB: "db" POSTGRES_HOST_AUTH_METHOD: "trust" and Dockerfile: # Pull base image FROM python:3.7 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /code # Install dependencies COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system # Copy project COPY . /code/ RUN pip install psycopg2-binary Please help to decide this problem.I read a lot information on stackoverflow about it.Changed code.But nothing to help me in this situation. -
I work on class,subject,chapter and question templating in django . now I have to get data in template foreign key in question to chapter to subject
My model is : class classes(models.Model): name = models.CharField(max_length=100) image = models.FileField(upload_to="class/",blank= True) class subject(models.Model): name = models.CharField(max_length=100) image = models.FileField(upload_to="subject/",blank= True) class classsubject(models.Model): name = models.CharField(max_length=100,blank= True) subject = models.ForeignKey(subject, on_delete=models.CASCADE) classes = models.ForeignKey(classes, on_delete=models.CASCADE) class chapter(models.Model): name = models.CharField(max_length=100,blank= True) class subjectchapter(models.Model): name = models.CharField(max_length=200,blank= True) chapter = models.ForeignKey(chapter, on_delete=models.CASCADE) classsubject = models.ForeignKey(classsubject, on_delete=models.CASCADE) class question(models.Model): subjectchapter = models.ForeignKey(subjectchapter, on_delete=models.CASCADE) here have template code of subject: <div class="owl-item language_item"> <a href="#"> <div class="flag"><img src="images/bangla.svg" alt=""></div> <div class="lang_name">***{{subject.name}}***</div> </a> </div> here will be the chapter from releted subject and question from releted chapter <div class="teacher d-flex flex-row align-items-center justify-content-start"> <div class="teacher_content"> <div class="teacher_name">***{chapter.name}***</div> <div class="teacher_title"><a href="instructors.html">***{question.name}***</a></div> <div class="teacher_title"><a href="instructors.html">আমরা পড়ার সময় কি করি?</a></div> <div class="teacher_title"><a href="instructors.html">আমরা খেলার সময় কি করি?</a></div> <div class="teacher_title"><a href="instructors.html">অ দিয়ে শব্দ কোনটি?</a></div> </div> </div> so now how i get the data of subject and chapter name in template in one view and in one page in html I need subject in releted class with releted chapter in a subject please give me the view and template code NB: here will be the data -
Django blocktrans problems with rendered variables
I have already translated in this project in the same way a number of similar templates in the same directory, which are nearly equal to this one. But this template makes me helpless. Without a translation tag {% blocktrans %} it properly works and renders the variable. c_filter_size.html {% load i18n %} {% if ffilter %} <div class="badge badge-success text-wrap" style="width: 12rem;"">{% trans "Filter sizing check" %}</div> <h6><small><p class="p-1 mb-2 bg-info text-white">{% trans "The filter sizing is successfully performed." %} </p></small></h6> {% if ffilter1 and ffilter.wfsubtype != ffilter1.wfsubtype %} <div class="badge badge-success text-wrap" style="width: 12rem;"">{% trans "Filter sizing check" %}</div> <h6><small><p class="p-1 mb-2 bg-info text-white"> If you insist on the fineness, but allow to reduce flow rate up to {{ffilter1.flowrate}} m3/hr the filter size and therefore filter price can be reduced. </p></small></h6> {% endif %} with a translation tag {% blocktrans %} it works neither in English nor in the translated language for the rendered variable. Other similar templates smoothely work. c_filter_size.html {% load i18n %} {% if ffilter %} <div class="badge badge-success text-wrap" style="width: 12rem;"">{% trans "Filter sizing check" %}</div> <h6><small><p class="p-1 mb-2 bg-info text-white">{% trans "The filter sizing is successfully performed." %} </p></small></h6> {% if ffilter1 and ffilter.wfsubtype … -
How to use django-taggit with custom html forms?
Many of you might have thinking that it is replication but believe me it is not. Nothing has answered my query. My major issue is I have nothing to do with "Forms.py". I have my own html templates and I am not getting how to successfully deploy django-taggit with it. My relevant code so far for you to look at: (models.py) from taggit.managers import TaggableManager class data(models.Model): user_id = models.IntegerField(null=False) title = models.CharField(max_length=200) description = models.CharField(max_length=200, null=True) tags = TaggableManager() (views.py) from taggit.models import Tag def add_data(request): if request.method == 'POST': id = request.user.id tags = request.POST["tags"] dress = Dress.objects.create(user_id = id, title = request.POST.get('title'), description = request.POST.get('description')) dress.save() for tag in tags: dress.tags.add() Everything is quite clear. I have observer that taggit has created two tables in db named, "taggit_tag" and "taggit_taggeditem". When I run the system, tags gets save in "taggit_tag" but nothing comes in "taggit_taggeditem". So for the reason when I try to show tags associated to certain data, I gets nothing. (views.py) def view_data(request, id): data= Data.objects.get(id = id) tags = Dress.tags.all() print("------content-------") print (tags) data = {"data": data, "tags":tags} return render(request, 'view.html', data) Empty query set appears when I print it. I believe my understanding … -
how to check for valid input django admin
I have models arranged like this, ModelA(models.Model): quantity = PositiveIntegerField(default=0, validators=[MinValueValidator(0)]) ModelB(models.Model): quantity = models.PositiveIntegerField() modela = models.ForeignKey(ModelA) And I have a signal that updates the quantity of ModelA every time modelB is updated. @receiver(post_save, sender=ModelB) update_quantity(instance, sender, **kwargs) When I do something like qty = instance.modela.quantity qty -= instance.quantity In a case the value becomes negative number, example in ModelA the quantity was 5 and I removed 6 from ModelA using ModelB quantity field ModelA raises a Validation error which is fine, My problem is how to parse that into the form of ModelB without the Error page. Being shown. I'm using the django admin for adding and editing. -
Is there a way in Django to test if a Cookie sent in request.META or request.COOKIES is httpOnly?
As the title suggests, I don’t think this is possible in Django:latest as of the time if writing, but is it possible to detect if a Cookie sent up in the request.HEADERS is httpOnly? -
Unable to remove callbacks in Bokeh Server (ValueError: callback already ran or was already removed, cannot be removed again)
I'm using Bokeh Server with Django to animate some charts that shows multiple series changing over time. I'm currently trying to automate the slider to progress the time series. Unfortunately I am experiencing two issues (that are probably related). The first is that the although the animation starts (the slider moves and 'play' changes to 'pause' on the button), the chart is not updated. The second is that any attempt to stop the slider (clicking on the 'pause' button) raise the error: ValueError: callback already ran or was already removed, cannot be removed again The slider continues to move. Django is making a request to the server for a server_document, passing 'pk' as an argument: views.py from django.shortcuts import render from django.http import HttpResponse from bokeh.embed import server_document def getchart(request, pk): key = pk script = server_document(url="http://localhost:5006/bokeh_server", arguments={"pk": pk, }, ) return render(request, 'testserver.html', {'script':script}) The bokeh server receives the request, finds the data associated with 'pk' then builds a chart with animation. main.py from bokeh.io import curdoc from copy import deepcopy from bokeh.plotting import figure from bokeh.embed import components from bokeh.models import ColumnDataSource, Slider, Button from bokeh.models.widgets import TableColumn from bokeh.layouts import column, row """ Get arguments from request … -
Separate Containers for Django, nginx and Postgres deployment
I want to deploy a website in completely isolated containers environment. Here are my requirements: A separate container for nginx and Let's encrypt certificate A separate container for PostgreSQL or MySql A separate container for Python/Django files Please guide me how can I achieve it. I searched over the web and I found most of the guys deploying nginx and Django files in same container which I don't need. Also, when I deploy nginx and Django in separate containers, how can I server the Static files? Thank you very much to everyone who contributes to it. Regards, Sharon -
Cart Item and Cart are not updadting properly
Here I created two models first one CartItem for the products that will be added to the CartItem and and if that product exists in the CartItem the quantity of the existing product will be updated. And the second model Cart that will store all the CartItem in that Cart Now the first issue that I am getting is - When the first product is added to the CartItem it is saved as 1 of test_product1. Now when I add the same product again its quantity is updated as 2 of test_product1. Its fine till here. I have 2 of those product. Now when I add the same product again, it's saved as 2 of test_product1. A new CartItem is created after I try to add more than 2 of the same prduct, it just keeps on creating new ones and saves it as 2 of test_product1 The second issue is when I add products to the CartItem the Cart is updated and saves all the CartItem. But when I change the product quantity, say removed or added 1 one. The total of the Cart doesn't change. Let me explain little better. a) I click Add to Cart -> the … -
Web scraper web app using Django on Heroku
I am creating web app that does two tasks: Data visualization on dashboard for user (web page) Scraping for data periodically (like 3 times a day for everyday) I have created the dashboard and deployed it on Heroku. For database, I am using postgres inside Heroku. My question is how should I structure the django project? Do you recommend to split the app into two projects? Or build the scraper in django? If this is the case, is it possible to have the scraper run all the time continuously along with the dashboard inside Heroku? Thanks -
Display a table/div without redirecting to another template(Django)
I am trying to display a new element on the website once the user clicks the button. I am not trying to redirect to view the content(like here: ibb.co/hLJm7p1, notice the link has changed) but instead add the table to an existing main page. Sorry if it is straight-forward but I cannot get my head around it.. Here is my code: root dir urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from chpstaff import views as chpstaff_views urlpatterns = [ path('admin/', admin.site.urls), path('signup/', chpstaff_views.signup, name='chpstaff_signup'), path('account/', chpstaff_views.account, name='chpstaff_account'), path('login/', auth_views.LoginView.as_view(template_name='staff/login.html'), name='chpstaff_login'), path('logout/', auth_views.LogoutView.as_view(template_name='staff/logout.html'), name='chpstaff_logout'), path('', include('trans_19.urls')), ] app urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name='trans_19_home'), path('account/', views.account, name='trans_19_account'), path('-<int:patient_pk>/', views.trips, name='trans_19_trips'), ] app views.py from django.shortcuts import render from django.views.generic import TemplateView from .models import Patient, Case # Create your views here. def home(request): context = { 'patients': Patient.objects.all() } return render(request, 'patients/home.html', context) def account(request): return render(request, 'patients/account.html') def trips(request, patient_pk): trips = Case.objects.filter(id=patient_pk) context = { 'trips': trips } return render(request, 'patients/trips.html', context) app, simplified home.html, which extends index.html <a href="{%url 'trans_19_trips' patient.pk %}"> <table class="ui celled table" style="text-align: center;"> <thead> <tr> … -
Set name of the file stored in FileField
Initial setup Several fields in a model MyModel store files: class MyModel(models.Model): icon2x = models.ImageField(...) logo2x = models.ImageField(...) By default Django overrides names of files during upload and applies a name of the field with optional random appendix if a file with this name already exists in storage. E.g. If we save two instances of MyModel with file image.png in icon2x field to clean database and storage: First instance of MyModel will store file in icon2x field with name icon2x.png. Second instance of MyModel will have to adjust to already existing icon2x.png file in storage and apply random appendix to the name which may look something like icon2x_AFtv0jG.png If for some reason it is desired to retrieve name of the file stored in a field without randomized appendix, following implementation does the job perfectly: def strip_name(field): name, extension = os.path.splitext(os.path.basename(field.name)) full_name = name.split('_')[0] + extension return full_name Case explanation Files stored in icon2x and logo2x fields are later used as content of zip archives. For an archive to be correctly imported into another system, names of files should comply with strict naming policy which requires certain format. This format contains symbols incompatible with Python syntax: e.g. an icon file should … -
Price translate for my Djagno eCommerce website
how e-commerce websites translate the product price? like US it price show in $, in India price show in INR. how do they do? -
Which django model is peroformance-optimised?
I have three models class modelA(models.Model): name=models.CharField(max_length=100) image=models.ImageField(upload_to='modelsA',blank=True) #some other fields class modelB(models.Model): name=models.CharField(max_length=100) image=models.ImageField(upload_to='modelsB',blank=True) #some other fields class modelC(models.Model): name=models.CharField(max_length=100) image=models.ImageField(upload_to='modelsC',blank=True) #some other fields I'm trying to create a model which holds preferred models instances of modelA,modelB and modelC. There are two approaches for solving this problem. Approach A I can create a new model D which can be initialised with field values from above models class modelD(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) name=models.CharField(max_length=100) image=models.ImageField(upload_to='shortcuts',blank=True) decider=models.IntegerField(default='0') #0=>shortcut from modelA #1=>shortcut from modelB #2=>shortcut from modelC Approach B Second approach is to hold the shortcuts in individual shortcut model and at time of fetching, serialise them after fetching into single list. class ShortcutA(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) shortcut=models.ForeignKey(modelA,on_delete=models.CASCADE) class ShortcutB(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) shortcut=models.ForeignKey(modelB,on_delete=models.CASCADE) class ShortcutC(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) shortcut=models.ForeignKey(modelC,on_delete=models.CASCADE) I cannot decide which approach would be faster.Approach A leads to extra fields while for approach B, i need to serialize them after fetching before sending them. Which approach is more optimised. Would be great if anyone can explain why? -
Can we add two password fields for validate password and confirm password using model fields in django
Actually i new to django framework. Here my doubt is, can we create two password fields for password validation one is password and second is confirm password for user registration template or can we manage only one password field. Let anyone please give the clarification for that. Here is example model: class new_user(models.Model): name = models.CharField() email = models.EmailField() password = models.CharField() confirmpassword = models.CharField() or else can we manage only one password field like below : class new_user(models.Model): name = models.CharField() email = models.EmailField() password = models.CharField() -
Increment Model Field Inside Get Or Create Django
I am developing a music web application where I am trying to calculate the number of times a song was played. When the play button is clicked, a function called getLink() is called. Here, I try to use get_or_create to update the PlayCount model, like so. h = PlayCount.objects.all() if len(h) == 0: u = PlayCount.objects.get_or_create( user=request.user.username, song=song, plays=1, )[0] u.save() else: flag = False for i in h: if i.song == song: u = PlayCount.objects.get_or_create( user=request.user.username, song=song, plays=plays + 1, )[0] u.save() flag = True break else: pass if flag is False: u = PlayCount.objects.get_or_create( user=request.user.username, song=song, plays=1, )[0] u.save() else: pass However, when I enter the else loop, 127.0.0.1:8000 returns play is not defined. How may I proceed? -
How to set command to populate django data through txt file DJANGO
thanks for your time: I got a model that has to be filled with 3 txt documents that got 40 rows each. the command should open each take the line, set the objects, save it, and be called again in a range 40: I'm beeing able to call it 40 times although i the 40 ones are tanking the same last line how can i set a count on the txt file to go to the next line when be called again? should i set a split to get the lines as a list? and set the line like a list index list[counter]? models.py: class MP4 (models.Model): nome = models.CharField(blank=True, max_length=100) url = models.URLField(blank=True, max_length=300) imagem = models.ImageField(blank=True, upload_to='') artista = models.CharField(blank=True, max_length=100, default='Unknown') seeder.py (command): class Command(BaseCommand): file_name = ['nome.txt', 'artista.txt', 'url.txt'] @classmethod def handle(cls, *args, **kwargs): counter = 0 for row in range(40): counter += 1 with open(cls.file_name[0]) as file: for linha in file: nome = linha with open(cls.file_name[1]) as file: for linha in file: artista = linha with open(cls.file_name[2]) as file: for linha in file: url = linha row = MP4( nome=nome, url=url, artista=artista, id=MP4.objects.latest('id').id + 1 ) row.save() nome.txt: Somewhere over the Rainbow ocean drive Michael … -
django rest serializer create save objects but return null
I am creating nested object in serializer it saves in the admin but in response return null value class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='question', null=True) index = models.CharField(max_length=250, null=True) value = models.CharField(max_length=250, null=True) serializer.py class QuestionSerializer(serializers.ModelSerializer): answer = AnswerSerializer(required=True) class Meta: model = Question fields = [#here my field name] def create(self, validated_data): answer = validated_data.pop('answer') instance = Question.objects.create(**validated_data) Answer.objects.create(question=instance, **question) return instance when I save in the postman, it returns this { "id": 28, #... "question": { "index": null, "value": null }, "user": 1 } but it indicates the value in the admin i do not know where I am missing something? How can I solve this issue? -
SQLite to PostgreSQL Not migrates - Django 3.0
Situation I have built Django 3.0 project with a couple of applications. Than I have created an application fro authentication acc All this has been done in an SQLite database Previously I have tried out a PostgreSQL database for the early application that was working fine but now when I switch of in the settings.py file the SQLite to PostgreSQL I get an error i I try to log in If I switch back the settings.py to SQLite everything works perfectly (ex.: authentication, logging in with user, user doing things on the website with it's own settings) I use decorators.py to keep logged in users visiting the login and signup pages and that gives error when I switch to postgresql. I only use here HttpResponse that the error message contains decorators.py from django.http import HttpResponse from django.shortcuts import redirect ... def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('NO AUTHORISATION TO BE HERE') return wrapper_func return decorator ERROR If I log in while settings.py uses PostgreSQL. If I log out everything works out fine again. If I use SQL lite I can … -
Django models reference another attribute within an attribute of the same class
I was trying to build a model for the profile details of the user of my django web app like: class UserDetails(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) profilePicture = models.ImageField(blank = True, upload_to='profile_pics/'+self.user.id+'/') country = models.CharField(max_length = 50, default='India') gender = models.CharField(max_length=10, default='NA') birthday = models.DateField(default=datetime.now()) phone = models.CharField(max_length=15) I have an image field in the above model and I want to upload the incoming images to the path profile_pics/<id of the user whose profile is being set up>/ within my media storage path. I tried to do that by specifying the upload_to attribute of the image field as upload_to = 'profile_pics/'+self.user.id+'/'. I am using AWS S3 for my media storage and I have put the necessary settings in my settings as: AWS_ACCESS_KEY_ID = 'myaccesskeyid' AWS_SECRET_ACCESS_KEY = 'mysecretaccesskey' AWS_STORAGE_BUCKET_NAME = 'mybucketname' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' When I try to make the migrations, I get the following error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 377, in execute django.setup() File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/suraj/Work/treeapp/treeapp-backend/treeEnv/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File … -
how to set config file for WSGIPassAuthorization On for token authentication in django with apache
I am hosting a ubuntu server for django application with djangorestframework with apache webserver. I have a problem with token authentication. All api's works fine on localhost but not works on the server. This response has come when calling to the server. {"detail":"Authentication credentials were not provided."} Some one told me to change its config file and add this line to config file because apache uses its own token authentication as default. WSGIPassAuthorization On So i have added this line to my config file and after that same response is coming. kindly tell me what to do next? views.py class ManageUserView(generics.RetrieveUpdateAPIView): serializer_class = serializers.UserSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_object(self): return self.request.user Serializers.py class UserSerializer(serializers.ModelSerializer): """ Serializer for the users object """ class Meta: model = get_user_model() fields = ('id', 'email', 'password', 'user_type') extra_kwargs = {'password': {'write_only': True, 'min_length': 8}} def create(self, validated_data): """ Create a new user with encrypted password and return it""" print(validated_data) return get_user_model().objects.create_type_user(**validated_data) def update(self, instance, validated_data): """ Update a user, setting the password correctly and return it """ password = validated_data.pop('password', None) user = super().update(instance, validated_data) if password: user.set_password(password) user.save() return user site.conf <VirtualHost *:80> ServerName www.shabber.tech ServerAdmin official.kisaziaraat@gmail.com ServerAlias shabber.tech DocumentRoot /var/www/html … -
Django query for a related object
I have two models Post and UserBookmarks. models.py of Project/App1 from App2 import UserBookmarks class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Title", max_length=20) content = models.TextField(verbose_name="Post Content", max_length=2000) ... bookmarks = GenericRelation(UserBookmarks, related_query_name='post') models.py of Project/App2 bookmarkable_models = models.Q(app_label='App', model='post') | models.Q(app_label='App', model='model-b') | models.Q(app_label='App', model='model-c') class UserBookmarks(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) content_type = models.ForeignKey(ContentType, limit_choices_to=bookmarkable_models, on_delete=models.CASCADE, null=True, blank=False) object_id = models.CharField(max_length=50, blank=False) content_object = GenericForeignKey('content_type', 'object_id') date_added = models.DateTimeField(auto_now_add=True, blank=False) Now I want to check if the user has already added the post to his bookmarks as my views.py but I don't understand how my query for this has to look like. Currently im doing something like this: if UserBookmarks.objects.filter(user__post__bookmarks=request.user).exists(): messages.error(request, 'You already added this Post to your Bookmarks.') return redirect('post_detail', pk=post.pk) Can smb. explain to me how this query has to look like in order to check if its already existing or not. currently im getting the following error: Cannot query "peter123": Must be "UserBookmarks" instance. -
Django access ForeignKey field and get their values
I`m trying to build a small webshop platform where a user can create a shop, select a category of products and add products to it. To achieve my goal I created this simplified models.py class Organization(models.Model): org_id = models.AutoField(primary_key=True) company_name = models.CharField(max_length=255) owned_by = models.OneToOneField(UserProfile, on_delete=models.CASCADE) def __str__(self): return f'{self.company_name} ORG' def get_absolute_url(self): return reverse('org-view', kwargs={'pk': self.org_id}) class Category(models.Model): CATEGORIES = ( ('electric', 'Electronics'), ('food', 'FrozenFood'), ('shoes', 'slippers') ) cat_name = models.CharField(max_length=255, choices=CATEGORIES) def __str__(self): return f'{self.cat_name} Category' def get_absolute_url(self): return reverse('cat-view', kwargs={'id': self.pk}) class Product(models.Model): org_id = models.ForeignKey(Organization, on_delete=models.CASCADE, blank=True, null=True) cat_name = models.ForeignKey(Category, on_delete=models.CASCADE) product_name = models.CharField(max_length=255) def __str__(self): return self.product_name In my views i want to keep the user on a single page where he can manage his shop. My current views.py: class OrganizationDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView, FormMixin): model = Organization queryset = Organization.objects.all() template_name = 'org/org_view.html' form_class = ProductForm def test_func(self): org = self.get_object() if self.request.user.profile == org.owned_by: return True return False def get(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data() pk = self.object.serializable_value('pk') product = Product.objects.filter(org_id=pk) return self.render_to_response(context) I need help to understand a few things: how to execute the queries to retrieve all of his products and be able to see the category … -
No transition from ASSIGNED viewflow
Previously i had an issue with viewflow as i was attempting to assign the process pk to a foreign key field. It seems like the issue has been resolved , however i am recieving another message error as seen below No transition from ASSIGNED It seems like the error may be coming from my flows.py : class Pipeline(Flow): process_class = PaymentVoucherProcess start = ( flow.Start( CreateProcessView, fields=["payment_code","bPBankAccount"] ).Permission( auto_create=True ).Next(this.approve) ) approve = ( flow.View( Signature, fields=["eSignatureModel"] ).Permission( auto_create=True ).Next(this.check_approve) ) check_approve = ( flow.If(lambda activation: activation.process.eSignatureModel) .Then(this.send) .Else(this.end) ) send = ( flow.Handler( this.send_hello_world_request ).Next(this.end) ) end = flow.End() def send_hello_world_request(self, activation): print(activation.process.payment_code) or my views.py: @flow_view def Signature(request): form = SignatureForm(request.POST or None) if form.is_valid(): esig = form.save(commit=False) signature = form.cleaned_data.get('signature') if signature: signature_picture = draw_signature(signature) signature_file_path = draw_signature(signature, as_file=True) esig.paymentVoucherProcess = request.activation.process esig.save() request.activation.done() return redirect(get_next_task_url(request, request.activate_next.process)) return render(request, 'cash/pipeline/jsig.html', { 'form': form, 'activation': request.activation }) Google doesn't give me much information on how to debug this , maybe someone with experience can assist me? I would greatly appreciate it! -
Python await outside async function
I'm trying to send data to my client from a Django channels consumer. I tried the following code: class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('test') def process_message(message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] print(Rate) await self.send_json(Rate) bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', process_message) bm.start() The problem with my actual code is that i'm getting the following error: SyntaxError: 'await' outside async function I think this happens because i'm using await inside a synchronous function, which is process_message(). I doon't know how to send the variable Rate in any other way. Is there a workaround? Can someone help me fix this issue?