Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add Yahoo Finance API with flask or django
My question is we can see in app.py as a (default="AMZN") i need to get an user input (or) a user can click on the company name to see more info and proceed further for each companys. I'm trying to learn flask and built a small app that contains a list of companies with some general info for each of them. The home page shows a list of all companies and then a user can click on the company name to see more info. I'm now trying figure out how APIs are consumed in flask by using Yahoo Finance to get some stock data about the company and display it on the page. It is fine flask or django web frame work. Also, I need a guidance from scratch. I am beginner. import yfinance as yahooFinance # Here We are getting Facebook financial information # We need to pass FB as argument for that GetInformation = yahooFinance.Ticker(input("enter iput here: " )) #GetInformation = yahooFinance.Ticker("FB") # whole python dictionary is printed here print(GetInformation.info) My code app.py from flask import Flask, redirect, url_for, render_template, request import yfinance as yf app = Flask(__name__) @app.route('/') def hello(): return 'Hello, World!' @app.route("/login", methods=["POST", "GET"]) def … -
How to implement multiple fields search in Django?
The problem is implementing a search across multiple fields. There is a sqllite database, there is a table and one search button on the page, the user enters a value into the fields (it is not necessary to fill in all the fields, it is filled in randomly). I'm just starting to learn django, don't judge strictly) Thanks! models # Год class Year(models.Model): title = models.CharField(max_length=4, verbose_name='Год') slug = models.SlugField(max_length=4, verbose_name='Slug Год', unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('year', kwargs={"pk": self.pk}) class Meta: verbose_name = 'Год' verbose_name_plural = 'Год' ordering = ['title'] # Наименвоание объекта class Subject(models.Model): title = models.CharField(max_length=100, verbose_name='Наименование объекта') slug = models.SlugField(max_length=100, verbose_name='Slug Наименование объекта', unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('subject', kwargs={"pk": self.pk}) class Meta: verbose_name = 'Наименвоание объекта' verbose_name_plural = 'Наименвоание объекта' ordering = ['title'] # Вид обследования class Surveys(models.Model): title = models.CharField(max_length=200, verbose_name='Вид обследования') slug = models.SlugField(max_length=200, verbose_name='Slug Вид обследования', unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('surveys', kwargs={"pk": self.pk}) class Meta: verbose_name = 'Вид обследования' verbose_name_plural = 'Вид обследования' ordering = ['title'] # Пост class Post(models.Model): title = models.CharField(max_length=100, verbose_name='Пост', blank=False, null=True, ) slug = models.SlugField(max_length=100, verbose_name='Slug Пост', unique=True) content = models.TextField(blank=True, verbose_name='Контент') created_at = models.DateTimeField(auto_now_add=True, verbose_name='Опубликовано') document … -
Problem with "import" when trying to create a Django project in virtual environment with VS code
This is the problem i have, including another one (the solution on this link didn't solve it): How to resolve 'Import "django.contrib" could not be resolved from source' in VS Code? As a bachelors project we are supposed to do an website with django and React. Our university wants us to do it with a lniux-based virtual environment. I followed this tutorial: https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react I can run the server with "python manage.py runserver" at first and it works, but when i try to import from for example ".model" errors arise and i can't run the server. I'm running windows and have installed "wsl" to get into a Linux virtual machine first. Then i install a virtual environment in the linux machine. I have set the python interpreter as the one i'm using in my VENV and it sticks. What can i try? Please help i've been stuck on this all day. I tried setting python interpreter as the one in the virtual environment, update python in the virtual environment, tried install the virtual environment in windows instead (a lot of other errors came up, won't be trying that again), tried follow differend tutorials which did it in different ways. The same … -
Form UpdateView and DeleteView and 3 hierarchical models
I am trying to create an 'Expense Tracker'. I have query regarding UpdateView and DeleteView and Models with 3 hierarchical levels. I was able to create the CreateView for the 'Expense' model, but the update and delete view are throwing a lot of errors. Can you please tell how to write the code for update and deleteview (for 'Expense' model). Models.py class Year(models.Model): year = models.IntegerField(choices=year_choices() ,validators=[MinValueValidator(1984), max_value_current_year], name='year', unique = True) def __str__(self): return str(self.year) class Meta(): ordering = ('-year','-year') class Month(models.Model): month = models.CharField(choices=month_choices(), max_length=264) month_year = models.ForeignKey(Year,related_name = 'month',on_delete=models.CASCADE) def __str__(self): return str(self.month) + ' ' + str(self.month_year) def get_absolute_url(self): return reverse("Expense_App:Year") class Meta(): unique_together = [['month','month_year']] class Expense(models.Model): Home_Expense = models.PositiveIntegerField() Groceries = models.PositiveIntegerField() Electronics = models.PositiveIntegerField() Snacks = models.PositiveIntegerField() Other = models.PositiveIntegerField() total = models.PositiveIntegerField() expense_month = models.ForeignKey(Month,related_name = 'expense', on_delete=models.CASCADE) def __str__(self): return str(self.expense_month) + ' ' + str(self.total) def get_absolute_url(self): return reverse("Expense_App:Year") Forms.py #forms.py class ExpensesForm(forms.ModelForm): class Meta(): model = Expenses fields = ('expenses','expense_month') def __init__(self, *args, **kwargs): month_year_id = kwargs.pop('month_year_id') super(ExpensesForm, self).__init__(*args, **kwargs) self.fields['expense_month'].queryset = ExpenseMonth.objects.filter(month_year_id=month_year_id) Views.py #createview for 'expense' model class ExpenseCreateView(CreateView): model = models.Expense form_class = ExpenseForm def get_form_kwargs(self): kwargs = super(ExpenseCreateView, self).get_form_kwargs() kwargs.update({'month_year_id': self.kwargs.get('pk')}) return kwargs Urls.py Update and … -
Django - unique_together with nested field in M2M
I have two model like A and B that have many-to-many relation on ids. B has a field like "type" and it maybe have many record with similar "type". i want manage this relation on every A related to one "type" no more. class throughModel(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE) b = models.ForeignKey(B, on_delete=models.CASCADE) class Meta: unique_together = ['a', 'b__type'] but dosen't work and i have no idea for implementation this. -
PGsql delete fields on a table and related on anoter in one command
In my django project i have two models: class Results(models.Model): device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) proj_code = models.CharField(max_length=400) res_key = models.SlugField(max_length=80, verbose_name="Message unique key", primary_key=True, unique=True) read_date = models.DateTimeField(verbose_name="Datetime of vals readings") unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL) and class VarsResults(models.Model): id = models.AutoField(primary_key=True) on_delete=models.CASCADE) key_res = models.ForeignKey(Results, related_name="keyres", on_delete=models.CASCADE) var_id = models.ForeignKey(ModbusVariable, null=True, on_delete=models.SET_NULL) var_val = models.CharField(max_length=400, blank=True) var_val_conv = models.CharField(max_length=100, blank=True, null=True) var_hash = models.CharField(max_length=400) has_error = models.BooleanField(default=False) so VarsResults has a key_res ForeignKey to table Results. I would, using PGSql create a query for delete ALL data starting from Results from a certain data and automatically delete the related rows in VarsResults like thisone: DELETE FROM Results WHERE read_date < "2022-01-01" (and delete also the related VarsResults rows) So many thanks in advance Manuel -
i have tried email validations and it was successfull but, I wantnthis error as popup alert
i have tried email validations and it was successfull but, I want this error as popup alert. forms.py class RegisterForm(forms.Form): MailID = forms.CharField(max_length=50, widget=forms.EmailInput(attrs={'class': 'form-control','placeholder': 'Enter Mail_ID'})) validation: def clean_MailID(self): mail = self.cleaned_data.get("MailID") rows = StudData.objects.filter(MailID=mail) if rows.count(): msg="mail already exits" raise ValidationError(msg) return mail i want to change error msg with email already exists to alert popup in window. -
CSRF cookie not set when calling POST request API view
I have encountered a weird behavior as it works with one view but does not with another. Django 3.2 and rest framework 3.13.1 are currently installed within the venv. When I call the view I get the error message: CSRF validation failed, reason CSRF cookie not set. This view uses an own authentication class that extends TokenAuthentication. class APIKeyAuthentication(authentication.TokenAuthentication): logger = logging.getLogger(__name__) def authenticate(self, request): # try to get api key via X-API_KEY api_key = request.META.get("HTTP_X_API_KEY") # try to get api key via Authorization if not api_key: api_key = request.META.get("HTTP_AUTHORIZATION") if not api_key: return None platform_id, api_user = self.validate_api_token(api_key) return api_user, None That class is used as default within rest framework: REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "api.authentification.APIKeyAuthentication", "rest_framework.authentication.BasicAuthentication", ), "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], Endpoints are: path("v1/combinedEntries", VerifyV1OrderView.as_view()), path("order/verify/", VerifyOrderView.as_view()), Classes: class VerifyV1OrderView(GenericAPIView): serializer_class = CombinedEntryV1Serializer authentication_classes = (APIKeyAuthentication,) and class VerifyOrderView(GenericAPIView): serializer_class = CombinedEntrySerializer authentication_classes = (APIKeyAuthentication,) so I do not understand the error I even removed the session authentication from the config but without any change. Has someone an idea what the problem could be? Thanks and regards. Matt -
Django Rest Framework - "You do not have permission to perform this action" in tests
I have Profile model which is custom user model. When I try to change it (sending patch request) via postman, all is ok. But when I try to do it in tests in returns "You do not have permission to perform this action" in response with ststus code 403. Here is code: # models.py class Profile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) user_name = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=50) surname = models.CharField(max_length=50) start_date = models.DateTimeField(default=timezone.now) image = models.ImageField(upload_to=photo_upload, default = 'profile_pics/default_avatar.jpg', null=True, blank = True) about = models.TextField(max_length=1024, blank = True, null = True) is_staff = models.BooleanField(default = True) is_active = models.BooleanField(default = True) objects = ProfileManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['user_name', 'first_name'] objects = ProfileManager() def get_absolute_url(self): return reverse('user', kwargs = {'pk': self.pk}) def __str__(self): return f'{self.user_name}' def save(self, *args, **kwargs): super().save(*args, **kwargs) if not self.image: self.image = f"{os.path.join(MEDIA_ROOT, 'profile_pics')}/default_avatar.jpg" else: img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path)` # serializer class class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ['email', 'user_name', 'first_name', 'surname', 'start_date', 'image', 'about', 'contacts'] read_only_fields = ['start_date', 'user_name'] # views.py class DetailUpdateDestroyUserAPI(RetrieveUpdateDestroyAPIView): Profile = apps.get_model('account', 'Profile') serializer_class = ProfileSerializer permisson_classes = [UserIsHimselfOrRO] lookup_field = 'user_name' def … -
Best practice using key stored in secret managers in django
I have db key stored in the aws secrets manager. My password is automatically generated and stored. const rdsCredentials: rds.Credentials = rds.Credentials.fromGeneratedSecret(dbInfos['user'],{secretName:`cdk-${targetEnv}-db-secret`}); const dbCluster = new rds.DatabaseCluster(this, 'Database', { engine: rds.DatabaseClusterEngine.auroraMysql({ version: rds.AuroraMysqlEngineVersion.VER_2_08_1 }), credentials: rdsCredentials, removalPolicy: cdk.RemovalPolicy.DESTROY, clusterIdentifier: dbInfos['cluster'], defaultDatabaseName :dbInfos['database'], instanceProps: { instanceType: ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE2, ec2.InstanceSize.SMALL), vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED, }, vpc, securityGroups:[mySecurityGroup], }, }); Now I can see the key in secrets manager and paste user/password in settings.config however it doesn't make use of secret manager. How can I use secret manager key in django ? -
When I trying to use *python* command in terminal it writes just 'Python' every time
When I trying to use python command in terminal it writes just 'Python' every time example: PS C:\Users\THE WORLD\Desktop\avtobot>python --version Python #Or PS C:\Users\THE WORLD\Desktop\avtobot>python manage.py makemigrations Python :Just like this how can I use this command But it is working when PS C:\Users\THE WORLD\Desktop\avtobot>py --version Python 3.10.4 But :) PS C:\Users\THE WORLD\Desktop\avtobot>py manage.py makemigrations Python and it is writing like this (and i tried to use python3 too) -
How to join 3 or more than 3 models in one single query ORM?
I am having 4 models linked with a foreign key, username = None email = models.EmailField(('email address'), unique=True) phone_no = models.CharField(max_length=255, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() def __str__(self): return self.email class personal_profile(models.Model): custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) picture = models.ImageField(default='profile_image/pro.png', upload_to='profile_image', blank=True) role = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(max_length=255, blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) def __str__(self): return str(self.pk) class academia_profile(models.Model): custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) education_or_certificate = models.CharField(max_length=255, blank=True, null=True) university = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return str(self.pk) class contact_profile(models.Model): custom_user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) country = models.CharField(max_length=255, blank=True, null=True) state = models.CharField(max_length=255, blank=True, null=True) city = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return str(self.pk) For extracting the data of those four models, I need to extract it by querying 4 times differently and then by passsing for different variables to HTML templates it something a hectic plus would be reducing the performance speed (I am sure!) My current queries be like user_base = CustomUser.objects.get(id=user_id) user_personal = personal_profile.objects.get(custom_user=user_id) academia = academia_profile.objects.get(custom_user=user_id) contact = contact_profile.objects.get(custom_user=user_id) Is it possible to get all of the four queries values in a single variable by hitting a single join query in ORM ? also, I want to extract just the country … -
failed to convert DJPADDLE_PUBLIC_KEY original message RSA key format is not supported
i'm trying to use Paddle as my payment subscription into my django website but its give me an error when i do /manage.py runserver failed to convert 'DJPADDLE_PUBLIC_KEY'; original message: RSA key format is not supported is anybody who can help me please. the settings.py file: DJPADDLE_PUBLIC_KEY '' DJPADDLE_API_KEY = '' DJPADDLE_VENDOR_ID = '' DJPADDLE_SANDBOX = False -
Add json response to a list
I am new in learning python requests and I am using GET METHOD and I am trying to insert returned json content in list, But it is showing TypeError: Object of type bytes is not JSON serializable I have tried many times and I also tried by adding into dictionary. views.py def request_get(request): url = "http://127.0.0.1:8000/api/items/" response = requests.get(url) results = [] results.append(response.content) return redirect('home') But it is showing TypeError: Object of type bytes is not JSON serializable I have also tried by using :- results = [] results.append({ 'response' : response.content }) Full Traceback Traceback (most recent call last): File "D:\apps - app\app\env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\apps - app\app\env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\app - app - app\env\lib\site-packages\django\http\response.py", line 653, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 238, in dumps **kw).encode(obj) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "D:\app - app - app\env\lib\site-packages\django\core\serializers\json.py", line 106, in default return super().default(o) File "C:\Users\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type bytes is not JSON serializable But it … -
how to make spaces paid for ads in my django website
" I have created Django app for e-commerce for multiple vendors but i need to make the same idea for selling spaces for ads which can client login and ask for specific space to post his ads after accepting from admin and paying his ads will be publish I am trying to make image field with description but I am confused when he can pay?" -
What are the best resources / Give me some good resources to master Django ORM (excluding Django Doc)?
I was wondering what are the recommended resources? preferably with plenty of exercises so I could get a lot of practice. Thank you! -
How to clear user specific cache in django?
I am using Django2.2.2 and django_redis for the cache backend. I had implemented cache in my API view according to this gist, and my views are here. from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from django.views.decorators.vary import vary_on_headers @method_decorator(cache_page(168 * 3600, key_prefix="posts")) @method_decorator(vary_on_headers("Authorization",)) def list(self, request, *args, **kwargs): return super(PostViewSet, self).list(request, *args, **kwargs) This method will cache the post list on the user basic for 7 days. I had a clear cache like this. from django.core.cache import cache cache.delete_many(keys=cache.keys("*.posts.*")) How can I delete only some specific user cache? I had tried django-clear-cache but it cleared all cache. Is there any technique for clearing the per-user cache? -
Counting many-to-many field returns wrong value (Django)
I have a model class Student: class Student(models.Model): ... and model class Course: class Course(models.Model) students = models.ManyToManyField(Student) I now want to filter Course based on number of Students associated with a course. I tried: Course.objects.annotate(student_count = Count('students')) But for some reason, student_count is always returning one. Let's say I create a course and add two students to it: s1 = Student.objects.create() s2 = Student.objects.create() m1 = Course.objects.create() m1.students.add(s1) m1.students.add(s2) print(Student.objects.all().first().students.count()) print(Student.objects.annotate(student_count = Count('students')).first().student_count Prints 2 1 Why are these two values different? How can I filter courses based on the number of students? -
how to get a variable value from form to python function in django from javascript
I am trying to scan QR code using javascript as shown below. this part is working fine: <title>Django Online Barcode Reader</title> <meta charset="utf-8"> {% csrf_token %} <script src={% static "html5-qrcode.min.js"%}></script> <style> .result{ background-color: green; color:#fff; padding:20px; } .row{ display:flex; } </style> <!--<form action="" method="POST">--> {% csrf_token %} <div class="row"> <div class="col"> <div style="width:500px;" id="reader"></div> </div> <div class="col" style="padding:30px;"> <h4>SCAN RESULT</h4> <!--<div id="result" name="result">Result Here</div>--> <output type="post" id="result" name="resutl" placeholder="qrCodeMessage"> </div> </div> <script type="text/javascript"> function onScanSuccess(qrCodeMessage) { document.getElementById('result').innerHTML = '<span class="result">'+qrCodeMessage+'</span>';} function onScanError(errorMessage) { //handle scan error } var html5QrcodeScanner = new Html5QrcodeScanner( "reader", { fps: 10, qrbox: 250 }); html5QrcodeScanner.render(onScanSuccess, onScanError); </script> But I need to pass the value of result variable to python function as following and print it but did not work. It does not print any! def userspage(request): if request.method == 'POST': result = request.POST.get("result") context = {} print(result) return render(request, 'users.html', context) I need your usual help to fix this. Thanks, -
Django web Deployment Failed. on azure
10:47:19 AM django-face-restore: ERROR: Could not find a version that satisfies the requirement torch==TORCH_VERSION+cpu (from versions: 1.4.0, 1.5.0, 1.5.1, 1.6.0, 1.7.0, 1.7.1, 1.8.0, 1.8.1, 1.9.0, 1.9.1, 1.10.0, 1.10.1, 1.10.2, 1.11.0) 10:47:19 AM django-face-restore: ERROR: No matching distribution found for torch==TORCH_VERSION+cpu 10:47:19 AM django-face-restore: WARNING: You are using pip version 21.1.1; however, version 22.0.4 is available. 10:47:19 AM django-face-restore: You should consider upgrading via the '/tmp/8da12d59fc3e034/antenv/bin/python -m pip install --upgrade pip' command. 10:47:19 AM django-face-restore: "2022-03-31 07:00:00"|ERROR|Failed pip installation with exit code: 1 10:47:21 AM django-face-restore: /opt/Kudu/Scripts/starter.sh oryx build /tmp/zipdeploy/extracted -o /home/site/wwwroot --platform python --platform-version 3.8 -i /tmp/8da12d59fc3e034 --compress-destination-dir -p virtualenv_name=antenv --log-file /tmp/build-debug.log 10:47:21 AM django-face-restore: Deployment Failed -
Django queryset for current year
I have my query written to get some thing from database and display on my website that query is getting all the data from db but what if i want to get the data particular to current year only def get(self, request, *args, **kwargs): filters = self.get_filters() result = Model.objects.all().filter(*filters).distinct().aggregate( t=Sum('t'), b=Sum('b'), ) result2 = Model.objects.all().filter(*filters).distinct().aggregate( past_due=Sum('balance', filter=Q(due_date__lt=timezone.now())) ) zero = Decimal('0.00') total = result['t'] or zero balance = result['b'] or zero past_due = result2['past_due'] or zero amount_received = t - b -
Send disconnect message to WebSocket in Django Channels
I am using Django==3.2.5 and channels==3.0.4. In the consumers.py I am using WebsocketConsumer class. My disconnect() method is executed After disconnecting the socket, which means the disconnect method is unable to send a response to the socket. I found a similar issue in this link but they are using AsyncWebsocketConsumer class. Is there a way to solve it using WebsocketConsumer class? I have the following code: class MeetingStatus_Consumer(WebsocketConsumer): def connect(self): self.room_name = self.scope["url_route"]["kwargs"]["id"] self.room_group_name = 'Booking_id_%s' % self.room_name # Adding room_name and group_name to the channel async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() # accept the request from frontend self.send(text_data=json.dumps({'status': "Websocket Connected"})) # send data to frontend def disconnect(self, *args, **kwargs): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) self.send(text_data=json.dumps({'status': "Websocket disconnected"})) -
Child terminated with exit code 2 for running celeryd service in production
i am using celery version 5.1.2 on Ubuntu 16.04 with python 3.8 and Django 3.0 .In my production i am unable run the schedule tasks. here is my /etc/systemd/celerd.conf # Name of nodes to start # here we have a single node CELERYD_NODES="worker1" # or we could have three nodes: #CELERYD_NODES="w1 w2 w3" CELERY_APP="mcam" # Absolute path to "manage.py" # CELERY_BIN="/home/ravi/deploy/mcam/mcam/server/mcam/manage.py" #CELERY_BIN="/home/ravi/.virtualenvs/lightdegree/bin/python manage.py celery" CELERY_BIN="/home/ravi/.virtualenvs/lightdegree/bin/celery" # How to call manage.py CELERYD_MULTI="celery beat" # Extra command-line arguments to the worker # m3.medium instance has 1 vCPU. Hence the concurrency is limited to 2 CELERYD_OPTS="--time-limit=300 --concurrency=4" # %N will be replaced with the first part of the nodename. CELERYD_LOG_FILE="/var/log/celery/%N.log" CELERYD_PID_FILE="/var/run/celery/%N.pid" this my /etc/systemd/system/celeryd.service [Unit] Description=Celery Beat Service After=network.target Requires=gunicorn.service rabbitmq-server.service [Service] #Type=forking User=ravi Group=ravi EnvironmentFile=/etc/systemd/celeryd.conf WorkingDirectory=/home/ravi/deploy/mcam/server/mcam #ExecStart=/home/ravi/.virtualenvs/lightdegree/bin/python manage.py celery -l debug -A mcam beat ExecStart=/home/ravi/.virtualenvs/lightdegree/bin/celery multi start ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS} #ExecStop=/home/ravi/.virtualenvs/lightdegree/bin/celery ${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ # --pidfile=${CELERYD_PID_FILE} ExecReload=/home/ravi/.virtualenvs/lightdegree/bin/celery ${CELERY_BIN} multi restart ${CELERYD_NODES} -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS} [Install] WantedBy=multi-user.target here are the commands what i used and error what i am getting sudo systemctl daemon-reload sudo systemctl reset-failed celeryd.service sudo systemctl restart celeryd sudo systemctl status celeryd ● celeryd.service - Celery Beat Service Loaded: loaded (/etc/systemd/system/celeryd.service; … -
TypeError: Field 'id' expected a number but got ['database']; ManyToManyField
I'm having a problem adding a set of objects on a ManyToMany field on my Question model, Question.tags. When passing the set of Tag instances on the line that contains question.tags.add(tags) the following error is raised: TypeError: Field 'id' expected a number but got ['database'] Why is adding the list of model instances to the ManyToMany field causing this error? class AskQuestionPage(Page): template_name = "posts/ask.html" extra_context = { 'title': "Ask a public question" } def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = QuestionForm return context def post(self, request): context = self.get_context_data() form = context['form'](request.POST) if form.is_valid(): profile = Profile.objects.get(user=request.user) form.cleaned_data['profile'] = profile tags = form.cleaned_data.pop("tags") question_tags = [] for name in tags: try: tag = Tag.objects.get(name=name) except Tag.DoesNotExist: tag = Tag.objects.create(name=name) finally: question_tags.append(tag) question = form.save() question.tags.add(question_tags) return SeeOtherHTTPRedirect( reverse("posts:question", kwargs={"id": question.id}) ) return self.render_to_response(context) class QuestionForm(ModelForm): title = CharField( min_length=20, max_length=80, widget=TextInput({"class": "question_input_shade fill_block_width"}), error_messages={"max_length": "The title of your question is too long"}, help_text="Concisely describe the issue" ) body = CharField( widget=Textarea(attrs={"class": "question_input_shade fill_block_width adjust_box"}), min_length=50, help_text="Clarify your question with as much detail as possible", error_messages={ 'required': "Elaborate on your question", 'min_length': "Add more info to your question" } ) tags = TagField( widget=MultiTagWidget( attrs={ "min_length": 1, "max_length": 25, … -
Searilizer in Django Rest framework isint working as expected
Following are my searlizers: #This isnt working as expected class ChatSearilizer(serializers.ModelSerializer): messages: MessageSearlizer(many=True) first_participant: serializers.SerializerMethodField() second_participant: serializers.SerializerMethodField( ) def get_first_participant(self, obj): return { "id": obj.first_participant.pk, "name": obj.first_participant.name, "photo": obj.first_participant.photo.file.url, } def get_second_participant(self, obj): return { "id": obj.second_participant.pk, "name": obj.second_participant.name, "photo": obj.second_participant.photo.file.url, } class Meta: model = Chat fields = "__all__" class MessageSearlizer(serializers.ModelSerializer): class Meta: model = Message fields = "__all__" Following are my models: class Chat(models.Model): first_participant = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name="first_participant") second_participant = models.ForeignKey( Profile, on_delete=models.CASCADE, related_name="second_participant") date_modified = models.DateTimeField(auto_now=True) class Message(models.Model): chat = models.ForeignKey(Chat, on_delete=models.CASCADE) sender = models.ForeignKey( to=Profile, on_delete=models.CASCADE, related_name="sender", null=True) # This null is temporary will remove it receiver = models.ForeignKey( to=Profile, on_delete=models.CASCADE, related_name="receiver", null=True) # This null is temporary will remove it text = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text class Meta: ordering = ["timestamp"] Following are the views: class UserChats(generics.ListAPIView): serializer_class = ChatSearilizer # get all the chats in which user is involved def get_queryset(self): return Chat.objects.filter(Q(first_participant=self.request.user.profile) | Q(second_participant=self.request.user.profile)) class ChatDetail(generics.RetrieveAPIView): serializer_class = ChatSearilizer def get_queryset(self): return Chat.objects.filter(pk=self.kwargs.get('pk')) class SendMessageView(generics.CreateAPIView): serializer_class = ChatSearilizer def post(self, request, *args, **kwargs): new_request = request chat_id = new_request.data["chat_id"] text = new_request.data["text"] sender = self.request.user.profile.pk receiver = new_request.data["receiver"] # check if chat_id is present in request body …