Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error :Forbidden (CSRF token missing or incorrect.) while using django rest framework
I use in my study project django rest framework.I get an error 403 Forbidden (CSRF token missing or incorrect, when I try to save using the POST method. Here is my code html <form id = "product_form" method = "post"> {% csrf_token %} <input type = "hidden" name = "id" id = "id"> <p>Назвние:<input name = "name" id = "name"></p> <p><input type = "reset" value = "Oчистить"></p> <input type = "submit" value = "Сохранить"> </form> Here is my code js: let productUpdater = new XMLHttpRequest(); productUpdater.addEventListener('readystatechange', () => { if (productUpdater.readyState == 4) { if ((productUpdater.status == 200) || (productUpdater.status == 201)) { listLoad(); name.form.reset(); id.value = ''; } else { window.alert(productUpdater.statusText) } } } ); name.form.addEventListener('submit', (evt) => { evt.preventDefault(); // let vid = id.value, url, method; let vid = id.value; if (vid) { url = 'http://127.0.0.1:8000/books/api_category/' + vid + '/'; method = 'PUT'; } else { url = 'http://127.0.0.1:8000/books/api_category/'; method = 'POST'; } let data = JSON.stringify({id: vid,nameCategory: name.value}); productUpdater.open(method, url, true); productUpdater.setRequestHeader('Content-Type', 'application/json'); productUpdater.send(data); }) Here is my views.py: @api_view(['GET', 'POST']) def api_products(request): if request.method == 'GET': productsAll = CategoryMaskarad.objects.all() serializer = CategorySerializer(productsAll, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = CategorySerializer(data=request.data) if serializer.is_valid(): serializer.save() return … -
How to see Django admin panel elements reordered in another tabs?
I want to reorder my django models in admin panel. I found the django-modeladmin-reorder package and installed it. I did everything according to the documentation, but I still have a problem. Reordering elements are being shown only on the main page of the website, if I click on a model to add or edit I see the old reorder. How can I see the new reorders in other tabs ? Good order: https://i.imgur.com/69N1CRs.png Bad order: https://i.imgur.com/9UYLXbX.png This is the code in settings.py ADMIN_REORDER = ( # First group {'app': 'website', 'label': 'Postări', 'models': ('website.Article', 'website.Research', 'website.Reports', 'website.Advocacy', 'website.Document', 'website.Domain', 'website.News', ) }, # Second group: same app, but different label {'app': 'website', 'label': 'Categorii', 'models': ('website.ArticleTag', 'website.ResearchTag', 'website.ReportsTag', 'website.AdvocacyTag', 'website.DocumentTag', 'website.DomainTag', 'website.NewsTag', ) }, {'app': 'website', 'label': 'Video', 'models': ('website.Video', 'website.MainVideo', ) }, {'app': 'website', 'label': 'Rapoarte', 'models': ('website.Reports', ) }, ) -
Django rest_framework DefaultRouter() class vs normal url
I'm using REST in Django, And I couldn't understand what is the main difference between classic URL and instantiating DefaultRouter() for registering URL by ViewSet. Is it possible to use classic URL in URLS.py instead of instantiating the object for a ViewSet View ? I just know HTTP method in ViewSet translate methods to retrieve, list and etc... Thanks for your help. -
django how to hide url and show renamed value?
I am using django-tables2 and trying to hide url and rename it on field. for example, url link is www.youtube.com but on actual field, I want it to show as 'link' instead of revealing entire url link. how do I achieve this? tables.py class MyVideoTable(tables.Table): class Meta: model = PPVideo fields = ('title', 'url') models.py class PPVideo title = models.CharField('Title', max_length=100, null=True) url = models.URLField('URL', max_length=150, null=True) -
Django AWS tutorial working for tutorial but not for full project
I'm following this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I follow the tutorial exactly, except use Django 4.0.3 and Python 3.8. It works for deploying a sample project, but when I make the settings.py exactly the same and try to put up my full project, I get the follow errors: health degraded 502 Bad Gateway nginx/1.20.0 failed (111: Connection refused) while connecting to upstream I tried to add gunicorn too but nothing was changing. But why would the same setup work for a simple sample project but not for my larger personal project? -
Python manage.py runserver is showing that python is not installed on my system
Whenever I run python manage.py runserver on my terminal I keep getting Python was not found, run without arguments to install from Microsoft -
How to add logic to a model getter that uses inheritance?
I have a model for a Task class Task(BaseTask): class Meta: db_table = 'task' verbose_name_plural = 'Tasks' def __str__(self): return f'Task {self.id}' def __unicode__(self): return f'Task {self.id}' that is inherited from BaseTask class BaseTask(BaseModel): class Meta: abstract = True task_status = models.CharField( choices=TASK_STATUS_CHOICES, blank=True, max_length=200, default=WAITING ) expiration_date = models.DateTimeField(blank=True, null=True, default=None) I want the task_status for Task to return FAILED if the current date is past the expiration date. I thought I could add a getter to Task like: def get_task_status(self): return FAILED if self.expiration_date and \ check_task_is_expired(self) else self.task_status but that doesn't seem to be working. How can I accomplish adding logic to task_status so it returns FAILED after the expiration date? I'm aware of @property but other models depend on BaseTask and Task so I don't want to change the field name. -
django-registration sending activation and reset emails
I am trying to send activation and reset email in Django, but I am facing some challenges and I would be grateful if someone could kindly help me out.onfigurations in settings.py file as below #setting.py EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST ='smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS =True EMAIL_HOST_USER ='email@gmail.com' EMAIL_HOST_PASSWORD ='gmailpasword' EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = ‘mail.mysite.com’ DEFAULT_FROM_EMAIL = 'noreply@mysite.com' EMAIL_HOST_USER = 'noreply@mysite.com' EMAIL_HOST_PASSWORD = 'my pass' EMAIL_USE_TLS = True EMAIL_PORT = port The first configuration is with Gmail which work fine in development but in production (shared Linux server) it does not work at all. The second configuration with an email I set up on webmail(cPanel) which is not working in either development or production. -
Getting the length of a certain row Django ORM
I am trying to query how many loans had a funded_date in the year 2021 and the total amount of those loans then show it on a template. I think I have the total amount right but am struggling on how to query and display how many loans had a funded_date in the year 2021 Views.py from django.shortcuts import render from .models import Loan import datetime from django.db.models import Sum def index(request): branch_cc = Loan.objects.filter(funded_date__year=2021) sum = branch_cc.aggregate(Sum('branch_cc')) number = branch_cc context = { 'all_loans': Loan.objects.all(), 'sum': sum, "branch_cc": branch_cc } return render(request, 'index.html', context) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1> {{sum}} <br> </h1> </body> </html> models.py from django.db import models class Loan(models.Model): funded_date = models.DateTimeField(auto_now_add=False, blank=True) respa_date = models.DateTimeField(auto_now_add=False, blank=True) loan_amount = models.FloatField(null=True, blank=True, default=None) branch_cc = models.IntegerField(default=0, blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
Having issues converting api json stream into an array in Flutter
The django api I am working with has the following actions user api (url = website/user/): action: CREATE_USER necessary params: action, email_address, password note: action = 0 action: LOGIN necessary params: action, email_address, password note: action = 1 action: CHANGE_PASSWORD necessary params: action, email_address, password, new_password note: action = 2 action: DELETE_USER necessary params: action, email_address, password note: action = 3 entry api (url = website/entry/): action: MAIN_PAGE necessary params: action note: action = 0 action: SEARCH_KEYWORD necessary params: action, keyword note: action = 1 action: FILTER_YEAR necessary params: action, first_year, second_year note: action = 0 note: if filter is for 1 year, first_year and second_year should be equal archive api (url = website/archive/): action: CREATE_ARCHIVE necessary params: action, email_address, password, keyword, frequency note: action = 0 note: frequency has to be 'daily', 'week', 'biweek', or 'month' action: DISPLAY_USER_ARCHIVES necessary params: action, email_address, password note: action = 1 note: to return entries pulled from archive, use action SEARCH_KEYWORD using the keyword saved in the archive action: DELETE_ARCHIVE necessary params: action, email_address, password, keyword note: action = 2 action: UPDATE_FREQUENCY necessary params: action, email_address, password, keyword, new_frequency note: action = 3 note: frequency has to be 'daily', 'week', 'biweek', or 'month' … -
Reduce stock in the database with django
I created a stock for the coffee beans in the database, and want to decrease the stock whenever CoffePods are created indicating the decrease of the beans stock. How to reduce the CoffeBeans stock in the database each time I create CoffePods which is received as a query parameter from the URL and what is the best practice in this case? views.py class PodsViewSet(viewsets.ModelViewSet): queryset = CoffePods.objects.all().order_by('id') serializer_class = CoffePodsSerializer serializer_class = CoffeBeansSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] filterset_fields = '__all__' def create(self, request, *args, **kwargs): print("Coffe Pod Created!") try: pods_pack_size = int(self.request.query_params.get('pack_size')) coffe_beans = CoffeBeans.objects.all()[0] if coffe_beans.capacity > 2.0 and coffe_beans.quantity > 4: if pods_pack_size == 1: coffe_beans.capacity -= 0.5 coffe_beans.quantity -= 1 coffe_beans.save() elif pods_pack_size == 2: coffe_beans.capacity -= 1.0 coffe_beans.quantity -= 2 coffe_beans.save() elif pods_pack_size == 3: coffe_beans.capacity -= 1.5 coffe_beans.quantity -= 3 coffe_beans.save() elif pods_pack_size == 4: coffe_beans.capacity -= 2.0 coffe_beans.quantity -= 4 coffe_beans.save() except Exception as e: raise e return Response(coffe_beans) models.py class CoffeBeans(models.Model): capacity = models.FloatField(validators=[MinValueValidator(0.0)], default=100) quantity = models.PositiveIntegerField(default=200) class Meta: verbose_name_plural = 'Coffe Beans' def __str__(self): return f"{self.capacity} KG - {self.quantity} Pack" -
DRF - How to concatanate serialized model with custom field
i need to concatanate serialized models with custom field = list[] i have a user_profile model and i want to know if particular user is "mine(active user's)" friend, in the users list (list_boolean = ["True", "False", "True"]) views.py class User_profile_view(APIView): def get(self, request): #this is example list which i need to link list_boolean = ["True", "False", "True"] query = User_profile.objects.all() User_profile.objects.filter(pk=1).delete() serializer_class = User_profile_serializer(query, many=True) return Response(serializer_class.data) models.py class User_profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) age = models.CharField(max_length=100) city = models.CharField(max_length=100) serializer.py class User_profile_serializer(serializers.ModelSerializer): class Meta: model = User_profile exclude = ["id"] is here any way to link particular list, to objects? it might be inside of the object (which is better) or outside -
Why I can't log in with this django login code, the message says: "Authentication credentials were not provided"
This is my views.py LoginView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def post(self, request): if request.method == 'POST': email = request.data.get('email', None) print(email) password = request.data.get('password',None) print(password) user = authenticate(request, email= "email", password= "pasword") print(user) if user : login(request, user) print("punto1") return Response(status=status.HTTP_200_OK) return Response( status=status.HTTP_404_NOT_FOUND) The output is: 403 Forbiden { "detail": "Authentication credentials were not provided." } -
Getting a database error when using Djongo to connect Django with MongoDB
Here is the entire error I am getting. I have tried looking everywhere for an answer and I am just lost. I have been trying to deploy, but I have been stuck with this error for months now. Internal Server Error: /profile/1/ Traceback (most recent call last): File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 784, in __init__ self._query = self.parse() File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 876, in parse raise e File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 933, in _select return SelectQuery(self.db, self.connection_properties, sm, self._params) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 116, in __init__ super().__init__(*args) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 62, in __init__ self.parse() File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 152, in parse self.where = WhereConverter(self, statement) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/converters.py", line 27, in __init__ self.parse() File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/converters.py", line 119, in parse self.op = WhereOp( File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/operators.py", line 475, in __init__ self._statement2ops() File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/operators.py", line 428, in _statement2ops op = self._token2op(tok, statement) File "/home/rlivermorejr/my_projects/screamingv2/.venv/lib/python3.9/site-packages/djongo/sql2mongo/operators.py", line 413, in _token2op raise SQLDecodeError djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: ('SELECT "post_app_screammodel"."id", "post_app_screammodel"."content", "post_app_screammodel"."posted_by_id", "post_app_screammodel"."creation_time" FROM "post_app_screammodel" WHERE "post_app_screammodel"."posted_by_id" = %(0)s OFFSET 3',) Params: ((1,),) Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most recent call last): File … -
Heroku set-cookie header was blocked because its domain attribute was invalid with regards to the current host url
I have a django app using htmx for a form and it's hosted on Heroku with Gunicorn as application server. I am getting 403 forbidden when I try to submit the form and tried a few different settings from reading the Django 4 docs. The form works on my local but not on Heroku. What else should I try so I can submit my htmx form with https on Heroku? my template <form hx-post="{{ request.path }}" hx-headers='{"X-CSRFToken":"{{ csrf_token }}"}' class="modal-content"> ... <script>document.body.addEventListener('htmx:configRequest', (event) => {event.detail.headers['X-CSRFToken'] = '{{ csrf_token }}';)</script> my settings.py CSRF_COOKIE_DOMAIN = '.herokuapp.com' CSRF_TRUSTED_ORIGINS = ['https://django-example.herokuapp.com','http://django-example.herokuapp.com'] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True Response headers csrftoken=GjeYwnfTwUGLzF7DSJWOoaJk1GHiSC3MffaLaornrd4ENDgKlokkHsyoIERTReB4; Domain=.herokuapp.com; expires=Mon, 06 Mar 2023 18:01:01 GMT; Max-Age=31449600; Path=/; SameSite=Lax; Secure ! This attempt to set a cookie via a set-cookie header was blocked because its domain attribute was invalid with regards to the current host url Heroku logs 022-03-07T18:59:13.184551+00:00 app[web.1]: Starting server 2022-03-07T18:59:16.297718+00:00 app[web.1]: [2022-03-07 18:59:16 +0000] [10] [INFO] Starting gunicorn 20.1.0 2022-03-07T18:59:16.298014+00:00 app[web.1]: [2022-03-07 18:59:16 +0000] [10] [INFO] Listening at: http://0.0.0.0:28553 (10) 2022-03-07T18:59:16.298062+00:00 app[web.1]: [2022-03-07 18:59:16 +0000] [10] [INFO] Using worker: sync 2022-03-07T18:59:16.301273+00:00 app[web.1]: [2022-03-07 18:59:16 +0000] [12] [INFO] Booting worker with pid: 12 2022-03-07T18:59:16.704678+00:00 … -
Python + Django + Gunicorn on AWS: 2 workers, worker terminated due to signal 15 -> Failed to boot
I'm pretty new using django + gunicorn + aws. Im struggling to find the problem on "signal 15 from gunicorn". Below are the log file from gunicorn. https://github.com/benoitc/gunicorn/issues/2755 -
Django - Cancel one delivery but when cancelling one it cancels all the deliveries
I'm trying to cancel one "posted" delivery when the user clicks on the button "cancel", but it cancels all the posted deliveries below is the views.py views html models Here is the list of deliveries I want to cancel one delivery and it automatically moves to the "Done/Cancelled Deliveries" page. -
How to upload multiple images to a form divided into 3 tabs?
I have a form divided into 3 tabs, in tab 2 and in tab 3 you have to upload multiple images respectively. The information that I have found about it, for the most part I do not understand and the one that I have seen easily, throws me many errors, can you help me tell me what I am doing wrong? Thanks models.py class Carro(models.Model): placas=models.CharField(max_length=255) marca=models.CharField(max_length=255) cliente= models.ForeignKey(Clientes, on_delete=models.SET_NULL, null=True) fotosCarro=models.ImageField(null=True, upload_to="images/") garantia=models.ImageField(null=True, upload_to="images/") fecha_registros = models.DateTimeField(default=datetime.now, null=True) def __str__(self): return f'{self.placas} {self.marca}{self.cliente}{self.fotosCarro}{self.garantia}' \ f'{self.fecha_registros}' forms.py class CarroForm(forms.ModelForm): class Meta: model=Carro fields = ['placas','marca','cliente','fotosCarro','garantia'] exclude = ['fecha_registros'] widgets = { 'placas': forms.TextInput( attrs={ 'class': 'form-control', } ), 'marca': forms.TextInput( attrs={ 'class': 'form-control' } ), 'cliente': forms.Select( attrs={ 'class': 'form-select' } ), 'fotosCarro':forms.FileInput( attrs={ 'class': 'type-file', 'multiple': True, 'id': 'file-input', 'onchange':'preview()', } ), 'garantia':forms.FileInput( attrs={ 'class': 'type-file', 'multiple': True, 'id': 'file-inputz', 'onchange': 'previewz()', # 'id':'pro-images', # 'click': "$('#pro-images').click()", } ), 'fecha_registros': forms.DateInput( attrs={ 'class': 'form-control', } ), } views.py def create_carros(request): form = CarroForm(request.POST or request.FILES) if request.method == 'POST': form = CarroForm(request.POST or request.FILES) fotosCarro = request.FILES.getlist('fotosCarro') garantia = request.FILES.getlist('garantia') for img in fotosCarro: Carro.objects.create(fotosCarro=fotosCarro) Carro.objects.create(garantia=garantia) images=Carro.objects.all() if form.is_valid(): form.save() return redirect('carros/index.html') return render(request, "carros/carros-form-add.html", {'form': form}) -
Json transferred in javascript
jsonData = { "a":{ "b":{ "c":"d" ,"e":"f" } ,"g":{ "h":"i" ,"j":"k" ,"m":"n" } ,"l":{ "o":"p" ,"q":"r" } } } } How do you create an array starting with a with JavaScript and transfer it to the jsondata function? -
Django CASCADE deletion not working and throws IntegrityError
I'm running into this bug with cascade deletion which is frustrating as I couldn't figure out what the root cause is. I use PostgresQL and I have the following database models: class Subdomains(models.Model): subdomainid = models.AutoField(db_column='subdomainid', primary_key=True) subdomainname = models.TextField(db_column='subdomainname', unique=True, ) class Meta: managed = True db_table = 'subdomains' class Dnsdata(models.Model): dnsid = models.AutoField(db_column='dnsid', primary_key=True) dnsa = models.TextField(db_column='dnsa', blank=True, null=True) subdomainid = models.ForeignKey(Subdomains,on_delete=models.CASCADE, db_column='subdomainid') class Meta: managed = True db_table = 'dnsdata' class Issues(models.Model): issueid = models.AutoField(db_column='issueid', primary_key=True) class Meta: managed = True db_table = 'issues' class Alerts(models.Model): alertid = models.AutoField(db_column='alertid', primary_key=True) subdomainid = models.ForeignKey(Subdomains,on_delete=models.CASCADE, blank=True, null=True, db_column='subdomainid') dnsid = models.ForeignKey(Dnsdata,on_delete=models.CASCADE, blank=True, null=True, db_column='dnsid') issueid = models.ForeignKey(Issues,on_delete=models.CASCADE, blank=True, null=True, db_column='issueid') # FK can be null class Meta: managed = True db_table = 'alerts' Whenever I try to remove an object from Subdomains table as follows: Subdomains.objects.filter(subdomainid=1).delete() it throws the following error: django.db.utils.IntegrityError: update or delete on table "subdomains" violates foreign key constraint "alerts_subdomainid_be56ec78_fk_subdomains_subdomainid" on table "alerts" DETAIL: Key (subdomainid)=(1) is still referenced from table "alerts". Please note that I've used on_delete=models.CASCADE and Foreign Keys in Alerts table can be null as well. -
crontab is not working with docker django
I'm setting up the cron job in my Django project, when I go to add the corn using this command python manage.py crontab add in my docker container so I got the following error. error: /bin/sh: 1: /usr/bin/crontab: not found settings.py INSTALLED_APPS = ( 'django_crontab', ... ) # Cron Jobs CRONJOBS = [ ('0 0 * * *', 'projects.views.notifications_cron') ] and I want to run my corn job after every 24 hours at 12am midnight. -
Getting an "Integrity Error Exception Value: NOT NULL constraint failed" in my Django application
I keep getting an integrity error for a particular table on my database - the review table, whenever a user tries to review a selected movie. I have gone through my codes line by line but can't seem to find the error. Please help! I always get an "IntegrityError Exception Value:NOT NULL constraint failed: movieworld_review.review_number" whenever the user tries to review a movie. I even tried setting the review_number to null=True, yet a new integrity constraint pops up, this time it is that "NOT NULL CONSTRAINT FAILED: MOVIEWORLD_REVIEW.MOVIE.ID". BELOW ARE MY CODES FOR THE VIEW AND MODEL: MODELS: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') picture = models.ImageField(upload_to = 'profile_images', blank=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) SIZE = 250, 250 if self.picture: pic = Image.open(self.picture.path) pic.thumbnail(SIZE, Image.LANCZOS) pic.save(self.picture.path) def __str__(self): return self.user.username class Genre(models.Model): title = models.CharField(max_length=30) slug = models.SlugField(null=False, unique=True) def get_absolute_url(self): return reverse('genres', args=[self.slug]) def __str__(self): return self.title def save(self, *args, **kwargs): if not self.slug: self.title.replace(" ", "") self.slug = slugify(self.title) return super().save(*args, **kwargs) class Movie(models.Model): imdbID = models.CharField(max_length=20, blank=True) Title = models.CharField(max_length=200) Year = models.CharField(max_length=25, blank = True) Genre = models.ManyToManyField(Genre, blank=True) Language = models.CharField(max_length=250, blank=True) Poster = models.ImageField(upload_to='movies', blank = True) Poster_url = models.URLField(blank=True) TotalSeasons … -
python3 manage.py migrate gives error about field even when it is deleted from the model class
Every time I run python3 manage.py migrate I get the same error about one of the fields in the model class. Even after deleting the field, the same error occurs. This is what the model class looks like: class Events(models.Model): name = models.CharField(max_length=200, null=True) date = models.DateTimeField(editable=True, null=True) sport = models.CharField(max_length=200, null=True) location = models.CharField(max_length=200, null=True) description = models.CharField(max_length=200, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) tags = models.ManyToManyField(Tag) num_seats = models.IntegerField(null=True, blank=True) creator = models.CharField(max_length=200, null=False) And this is what the error looks like: TypeError: int() argument must be a string, a bytes-like object or a real number, not 'IntegerField' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/laithtahboub/Desktop/Programming/Django/events_project/manage.py", line 22, in <module> main() File "/Users/laithtahboub/Desktop/Programming/Django/events_project/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 373, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 417, in execute output = self.handle(*args, **options) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/base.py", line 90, in wrapped res = handle_func(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 253, in handle post_migrate_state = executor.migrate( File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/executor.py", line 126, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/migrations/executor.py", line 156, in _migrate_all_forwards state … -
Django Query many to many field count miscalculation
I am creating a Django Blog Website and I am stuck at one point finding the no of likes on a specific post. I have created a webpage where all the posts are displayed. Now the problem I am facing is the no of likes are getting calculated wrong. Post Model -> class Post(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) title = models.CharField(max_length=255) description = models.CharField(max_length=1000,null=True) Tags = models.CharField(max_length = 255,null=True,blank=True) Created_date = models.DateTimeField(auto_now_add=True) Updated_date = models.DateTimeField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) Likes = models.ManyToManyField(to=User, related_name='Post_likes') favourites = models.ManyToManyField(to=User,blank=True,related_name="favourite") def __str__(self): return self.title Query in Views.py file to fetch all the posts -> posts = Post.objects.select_related().prefetch_related('images_set').annotate(Count('comments_post')).annotate(Count('Likes')).all() Now when I see the post.Likes__count in template it shows wrong count of 6 for one specific post but when I use post.likes.count() it shows count of 3. for other posts they both show same result. I am unable to find out why it is happening. This is the result for that specific post -> {'post_id': 22, 'user_id': 1, 'title': 'wkjdfh', 'description': 'kjwdfn', 'Tags': '.,smdf,m', 'category': <Category: Shoes>, 'userName': 'admin', 'images': <QuerySet [<Images: Images object (10)>, <Images: Images object (11)>, <Images: Images object (12)>, <Images: Images object (13)>]>, 'comments_count': 6, 'likesCount': 6, 'actualLikeCount': 3} This is very … -
How to safely execute user-written code in the backend?
I'm trying to build a Django web application that allows users to write Python code and runs that in the backend, kinda like how an IDE would work. I'm just wondering, what security risks does this come with? I'm sure there are plenty, the user could literally do anything with that code, so what would be a good solution to safely do this? Would running it inside a Docker container be a good solution?