Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make endpoint view in django to get queryset for autocomplete?
I am trying to make queryset for autocomplete search using jquery UI. I wrote a function based view which according to me should work ,but its not working as it should. when i type valid word it redirects me where search results should be shown but there i get error AttributeError: 'Branches' object has no attribute 'FIELD' Branches is my model class Branches(models.Model): ifsc = models.CharField(primary_key=True, max_length=11) bank = models.ForeignKey(Banks, models.DO_NOTHING, blank=True, null=True) branch = models.CharField(max_length=250, blank=True, null=True) address = models.CharField(max_length=250, blank=True, null=True) city = models.CharField(max_length=50, blank=True, null=True) district = models.CharField(max_length=50, blank=True, null=True) state = models.CharField(max_length=26, blank=True, null=True) my views.py def search_ifsc(request): if request.is_ajax(): q = request.GET.get('q', '').capitalize() search_qs = Branches.objects.filter(ifsc__startswith=q) results = [] print(q) for r in search_qs: results.append(r.FIELD) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) urls.py path('ajax/search/' , views.search_ifsc, name='search_view') template <div class="position-absolute top-50 start-50 translate-middle"> <nav class="navbar navbar-light bg-light"> <div class="container-fluid" class="ui-widget"> <form id="search" method="POST" action="http://127.0.0.1:8000/ajax/search/"> <!-- {% csrf_token %} --> <input type="text" class="form-control" id="q" name="q"> <button type="submit" class="btn btn-default btn-submit">Submit</button> </form> </div> </nav> </div> <script type='text/javascript'> $(document).ready(function(){ $("#q").autocomplete({ source: "http://127.0.0.1:8000/ajax/search/", minLength: 2, open: function(){ setTimeout(function () { $('.ui-autocomplete').css('z-index', 99); }, 0); } }); }); I get this error when i … -
AttributeError Implementing First Serializer: 'QuerySet' object has no attribute 'name'
I've just built a Item (product) model for my project's eCommerce page, an ItemDetailsView which returns individual items and an ItemApiView which is meant to create/retrieve/update/delete. When I make a get request to get ItemApiView I expect it to return a full list of items in my database. However, I am getting the following error: AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `ItemSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance. Original exception text was: 'QuerySet' object has no attribute 'name'. "name" is a field in my Item model. Here is the full model: class Item(BaseModel): """ Item that can be purchased """ name = models.CharField(max_length=150) description = models.TextField(blank=True) price = models.DecimalField(max_digits=4, decimal_places=2) image = models.ImageField(upload_to="images/", default="images/default.png") category = models.ForeignKey(Category, on_delete=models.PROTECT, null=True) is_active = models.BooleanField(default=True) quantity = models.IntegerField(null=True, blank=True, default=0) discount = models.FloatField(default=0.0) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural = "Products" ordering = ("-created",) def get_absolute_url(self): return reverse("store:product_detail", args=[self.slug]) def __str__(self): return "{}".format(self.name) Here is the ItemApiView. Only the "Get" method corresponds to my specific problem but I included the full view because I am open to critiques on the … -
Problem in creating Custom Model Django superuser
Iam using Django 3.2.4 with rest_framework. I have been trying to create a custom user model for my project, which successfully migrates. But while creating a super user Iam getting a error TypeError: create_superuser() missing 1 required positional argument: 'username' My models looks like this: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique=True, max_length=254, ) first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=15) contact = models.IntegerField(unique=True) date_joined = models.DateTimeField(default=datetime.now) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] since I want my custom user model, why django is asking for default username as its default? Where am I going wrong here? -
Hi Django Community, I am facing issue on deleting individual comments from blog posts as superuser?
I am facing issue on deleting individual comments from blog posts as superuser? I have Cross Icon which i want functionality in to delete comment. It would be great if someone help me with the flow i am doing other tasks.As I want be stay in Simple. This is my blog's models.py code class Post(models.Model): Title=models.CharField(max_length=50) slug = models.SlugField(unique=True,null=True,blank=True) Meta_Tags = models.CharField(max_length=200,null=True) Description=models.TextField() Category=models.CharField(max_length=50) Body=RichTextUploadingField() Date=models.DateField(auto_now_add=True) Views=models.IntegerField(default=0,null=True) Likes=models.IntegerField(default=0,null=True) Dis_Likes=models.IntegerField(default=0,null=True) CommentsCounts=models.IntegerField(default=0,null=True) def __str__(self): return self.Title + " | " + str(self.Date) def createslug(instance,new_slug=None): slug=slugify(instance.Title) if new_slug is not None: slug=new_slug qs = Post.objects.filter(slug=slug).order_by("-id") exists=qs.exists() if exists: new_slug = "%s-%s" %(slug,qs.first().id) return createslug(instance,new_slug=new_slug) return slug def pre_save_post_receiver(sender,instance,*args, **kwargs): if not instance.slug: instance.slug=createslug(instance) pre_save.connect(pre_save_post_receiver,Post) class Comment(models.Model): Post=models.ForeignKey(Post, on_delete=models.CASCADE,null=True) Name=models.CharField(max_length=50,null=True) Body=models.TextField(null=True) Time=models.DateTimeField(auto_now_add=True,null=True) def __str__(self): return str(self.Post) + " | " + self.Body + " | " + self.Name + " | " + str(self.Time) This is my blog's views.py code def blogdetail(request,slug): post=Post.objects.get(slug=slug) comment=Comment.objects.filter(Post=post).order_by('-id') post.Views +=1 if 'Like' in request.POST: post.Likes +=1 if 'DisLike' in request.POST: post.Dis_Likes +=1 if 'Comment' in request.POST: post.CommentsCounts +=1 Name=request.POST.get('name',default="Anonymous") Body=request.POST.get('comment') Comments=Comment(Name=Name,Body=Body,Post=post) Comments.save() post.save() context={ 'post':post, 'comment':comment, } return render(request,'blogdetail.html',context) This is my blog's template code {% for comment in comment %} <div class="comment-card my-3"> <span><i class="fas fa-user text-secondary"></i></span> … -
Need assistance in designing Django model for a school management system app
I am trying to create a school management app, and I want to have place where a school admin can create a weekly schedule for a class. I have the below structure in mind for this. { "grade": 1, "shortBreak": "10:00am - 10:15am", "longBreak": "1:00pm - 2:00 pm", "monday": [ { "time":"09:00am - 09:30am", "subject":"English" }, { "time":"09:30am - 10:00am", "subject":"Math" },{ "time":"10:15am - 10:45am", "subject":"Science" }, ], "tuesday":[ { "time":"09:00am - 09:30am", "subject":"Maths" }, { "time":"09:30am - 10:00am", "subject":"Social Sciene" },{ "time":"10:15am - 10:45am", "subject":"Sports" }, ], "Wednesday":[ { "time":"09:00am - 09:30am", "subject":"Maths" }, { "time":"09:30am - 10:00am", "subject":"Social Sciene" },{ "time":"10:15am - 10:45am", "subject":"Sports" }, ], "Thursday":[ { "time":"09:00am - 09:30am", "subject":"Maths" }, { "time":"09:30am - 10:00am", "subject":"Social Sciene" },{ "time":"10:15am - 10:45am", "subject":"Sports" }, ], "Friday":[ { "time":"09:00am - 09:30am", "subject":"Maths" }, { "time":"09:30am - 10:00am", "subject":"Social Sciene" },{ "time":"10:15am - 10:45am", "subject":"Sports" }, ], "Saturday":[ { "time":"09:00am - 09:30am", "subject":"Maths" }, { "time":"09:30am - 10:00am", "subject":"Social Science" },{ "time":"10:15am - 10:45am", "subject":"Sports" }, ], } The challenge I am facing is that I don't know how to add array fields in Django models and how to have multiple objects in an array and store it in … -
Download zip folder using ajax and celery task
I have a view (see below) that enable users to download zip folder with filetered data and it works. To improve performances, I want to change to an asynchronous task using ajax and celery task with celery-progress to display a progress bar. But I can not return Httpresponse (with zip file attached) using celery task as I do with the 'classical view' so I do not really know how to proceed. I thought about making and storing zip folder on server and when task is finished, the view return the zip folder. But I do not want to store multiple zip folders on server. I also thought about another scheduled task that could remove zip folders on a regularly basis... but this sound very 'complicated' process... What would be the best approach to do this? def export(request): ... # path to study directory to be pass in argument path = './exports/'+ study_name +'/' + database_name + '/archives/' + selected_import + '/' # retrieve the list of all files in study directory excluding 'archives' directory listOfFiles = getListOfFiles(path) # Create zip buffer = io.BytesIO() zip_file = zipfile.ZipFile(buffer, 'w') # if Data checkbox is checked, zip include the data files if data … -
Average of DateTimeField Django
class Foo(models.Model): ... a=models.IntegerField() timestamp=models.DateTimeField(auto_now_add=True) I want the average of timestamp field and when making a query Foo.objects.filter(a=1).values('timestamp','a').aggregate(Avg('timestamp')) its giving me error 'decimal.Decimal' object has no attribute 'tzinfo'. Can anyone help me how can I fix this or tell me a way how can I take the average of DateTimeField? -
Django, how to run a command through Windows Task Scheduler
How to schedule and run a specific command in django using Windows Task Scheduler. My django project is not currently local server deployed but using the manual set up just like activating the virtual environment and then typing the python manage.py runserver on terminal rather deploying through xampp or laragon. But i am bit confused on how to achieve to schedule and run a command like python manage py get_source through the use of Windows Task Scheduler. -
How to overrite the admin change_view Django
I want to overrite the admin change_view so I can add more items to the context. Apparently, my attempted solutions give me an error that says: if not response.has_header('Expires'): AttributeError: 'NoneType' object has no attribute 'has_header' My attempted solution is below. Any help will def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = dict( name='John' ) super().change_view(request, object_id,extra_context=extra_context) -
"The submitted data was not a file. Check the encoding type on the form"- Django rest framework
I have an addproduct api in which frontend is sending a multipart/formdata in a post axios call. The image is sent in a binary when I checked the data. But I got the following error. I have made a custom parser, but still got the error. The error is. "The submitted data was not a file. Check the encoding type on the form" The data sent is like this. category[0]: 2 category[1]: 1 brand: 4 collection: 3 availability: not_available warranty: local_seller_warranty service: free_shipping rating: 5 best_seller: true top_rated: true featured: true main_product_image: (binary) merchant: 9 My custom parser: class MultipartJsonParser(parsers.MultiPartParser): def parse(self, stream, media_type=None, parser_context=None): result = super().parse( stream, media_type=media_type, parser_context=parser_context ) data = {} # print(result.data) # for case1 with nested serializers # parse each field with json raw =[] flag = True for key, value in result.data.items(): if type(value) != str: data[key] = value continue if '{' in value or "[" in value: try: data[key] = json.loads(value) except ValueError: data[key] = value if '[' in key : x=0 s=key while x < len(key): s = s.translate({ord('['): None}) s = s.translate({ord(']'): None}) s = s.translate({ord('0'): None}) s = s.translate({ord('1'): None}) s = s.translate({ord('2'): None}) s = s.translate({ord('3'): None}) s … -
How to load an api response faster and using it in pandas for analysis in django?
I am new to django and currently working on a project which includes data analysis using pandas and showing it on a website. Though it is taking about 1 minute to load on my local server . How can I do it faster ? views.py def contest_analysis(request,con_id): #rating change statistics url = "https://codeforces.com/api/contest.ratingChanges?contestId="+con_id rating_changes = pd.DataFrame(get_api_response(url)) rating_changes = rating_changes.drop(columns=["contestName", "ratingUpdateTimeSeconds", "contestId"]) rank_mapping(rating_changes) participants = rating_changes['oldranking'].value_counts().to_dict() print(participants) #contest all submissions statistics url ="https://codeforces.com/api/contest.standings?contestId="+con_id+"&showUnofficial=false" data = get_api_response(url) df = pd.DataFrame(data["rows"]) df = df.drop(columns=["points", "successfulHackCount", "unsuccessfulHackCount"]) new_columns=problem_sep(df) print(new_columns.keys()) problems2 = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in new_columns.items()])) final_dataset = pd.concat([rating_changes, problems2], axis=1) return render(request,"cheforces/contest_analysis.html",{"p" : con_id, "participants" : participants,}) get_api_response function def get_api_response(url): try: with request.urlopen(url) as response: source = response.read() data = json.loads(source) data = data['result'] return data except: raise Http404('Codeforces Handle Not Found!!!') I am using codeforces API . -
Django Query to select multiply count
Can any member can help to solve the bellow particular problem: select count(total_lead), count(pending), count(progress),count(closed) from leads where user=user How do I achieve this query in Django ORM ? Any help in highly appreciated. Thanks Regards, -
Querying in django models
I have two models user and posts. Each post is associated to a user and user can follow each other and the user model contains a field called is_private_profile depending on which user's posts are visible to eveyone or only to those who follow the user. I want to fetch all the posts whose authors have public profile and the posts for users with private profile only if the user who wants the post follows him class Posts(models.Model): author = models.ForeignKey(User, verbose_name=_( "Author"), on_delete=models.CASCADE, related_name="posts") caption = models.TextField(_("Caption")) created_at = models.DateTimeField( _("Created At"), auto_now=False, auto_now_add=True) updated_at = models.DateTimeField( _("Updated At"), auto_now=True, auto_now_add=False) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_("Email"), max_length=254, unique=True) follows = models.ManyToManyField("self", verbose_name=_( "Followers"), symmetrical=False, related_name='followed_by') is_private_profile = models.BooleanField( _("Is Private profile"), default=False) -
How to get data from entity that exists only in session with Django?
I have to store order history as sets of goods in order. I intended to achieve this by copying contents of the cart to model I've created using object.create. But cart was written by someone else and doesn't have actual model as it exists only within session. How do I retrieve data from it to put it into my Order object? My cart class: class Cart(object): def __init__(self, request): """ Инициализируем корзину """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): """ Добавить продукт в корзину или обновить его количество. """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # Обновление сессии cart self.session[settings.CART_SESSION_ID] = self.cart # Отметить сеанс как "измененный", чтобы убедиться, что он сохранен self.session.modified = True def remove(self, product): """ Удаление товара из корзины. """ product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): """ Перебор элементов в корзине и получение продуктов из базы данных. """ product_ids = self.cart.keys() # получение объектов product и … -
Django delete superclass update or delete on table violates foreign key constraint
I have two django models, one subclassing another, class A(models.Model) : . . class B(A) : . . the problem is when I'm deleting class A I'm getting update or delete on table "a" violates foreign key constraint "b_a_ptr_id_53f8796d_fk_a" on table "b" Shouldn't the delete automaticly take out the row on table B pointing to the deleted element? Can anyone guide me through this please. -
ERROR (EXTERNAL IP): Internal Server Error: /
We currently have a CA setup with django connected through its API (dogtag). We recently set up a new subordinate CA and tried to redirect django to this new IP, however we are receiving the following error when submitting a CSR request to my CA using django: KeyError at / 'Output' Request Method: POST Request URL: https://10.10.50.4/ Django Version: 2.2.14 Python Executable: /app/PKIWeb/venv/bin/python3.6 Python Version: 3.6.6 Python Path: ['/app/PKIWeb', '/app/PKIWeb/venv/bin', '/app/PKIWeb/venv/lib64/python36.zip', '/app/PKIWeb/venv/lib64/python3.6', '/app/PKIWeb/venv/lib64/python3.6/lib-dynload', '/usr/lib64/python3.6', '/usr/lib/python3.6', '/app/PKIWeb/venv/lib/python3.6/site-packages'] Server time: Sáb, 26 Jun 2021 21:14:30 -0400 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'core', 'api', 'django_extensions', 'widget_tweaks', 'rest_framework', 'rest_framework_api_key', 'drf_yasg'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'camaracomercio.middleware.CsrAPILocaleMiddleware'] Traceback: File "/app/PKIWeb/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/app/PKIWeb/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/app/PKIWeb/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/PKIWeb/venv/lib/python3.6/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/app/PKIWeb/venv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 97. return handler(request, *args, **kwargs) File "/app/PKIWeb/venv/lib/python3.6/site-packages/django/views/generic/edit.py" in post 142. return self.form_valid(form) File "/app/PKIWeb/core/views.py" in form_valid 39. cert_request_infos = self.request_ca_certificate(data, profile) File "/app/PKIWeb/core/views.py" in request_ca_certificate 62. enroll_request = client.create_enrollment_request(profile, data) File "/app/PKIWeb/venv/lib/python3.6/site-packages/pki/__init__.py" in handler 304. return fn_call(inst, *args, **kwargs) File "/app/PKIWeb/venv/lib/python3.6/site-packages/pki/cert.py" in create_enrollment_request 962. enrollment_template = self.get_enrollment_template(profile_id) File "/app/PKIWeb/venv/lib/python3.6/site-packages/pki/__init__.py" in … -
How to update Django model data
I am creating an application that gives users donations and points after they fill out the form on my donate.html. I want to know how I can add data to the Django integer field after the ins.save in my code. For example, if the donation field is equal to 3, after the ins.save, I want to add 1 to it and therefore it will be equal to 4. My code is down below. Thank you to everyone who helps! Donate View: def donate(request): if request.method == "POST": title = request.POST['donationtitle'] phonenumber = request.POST['phonenumber'] category = request.POST['category'] quantity = request.POST['quantity'] location = request.POST['location'] description = request.POST['description'] ins = Donation(title = title, phonenumber = phonenumber, category = category, quantity = quantity, location = location, description = description, user=request.user, ) ins.save() return render(request,'donate.html') Model: (I want to add to this data after the ins.save) class UserDetail(models.Model): donations = models.IntegerField(blank=True, null = True,) points = models.IntegerField(blank=True, null = True,) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) -
How can I iterate over object instances associated with another object through many-to-many relationship in Django?
I have a model JobEntry which has a many-to-many relationship with another model ServiceItemStats. Their implementation is: class JobEntry(models.Model): # PK: id - automatically assigned by Django. stats = models.ManyToManyField(ServiceItemStats, blank=True) #Many-to-many relationship class ServiceItemStats(models.Model): service_stats_name = models.CharField(primary_key=True, max_length=20) service_stats_estimate_duration = models.IntegerField() # Many-to-many relationship with JobEntry. def __str__(self): return self.service_stats_name I am trying to get all service_stats_name field values of ServiceItemStats associated with a particular JobEntry in a table by using a loop: <table class="table"> <thead class="thead-dark"> <tr class="table-light"> <th class="lead"><strong>Assigned service items:</strong></th> <td class="lead"> {% for stat in JobEntry.stats_set.all %} {{ stat.service_stats_name }} <br> {% empty %} No service items assigned. {% endfor %} </td> </tr> </thead> </table> This is all done in a JobDetailView: class JobDetailView(DetailView): context_object_name = 'jobDetail' model = JobEntry template_name = 'jobs/job_detail.html' I keep getting "No service items assigned" although if I go through Django admin, I can see that there actually are instances of ServiceItemStats associated with a JobEntry. I am not sure what am I doing wrong here, any help would be appreciated. -
ModuleNotFound error trying to open Django app in Heroku- issue with gunicorn setup?
I've been building my first Django project (just running it locally so far using runserver), and I'm taking the steps to host it on Heroku, adding gunicorn. The build succeeds, but when I try to open the app, the Heroku logs show an exception in worker process: ModuleNotFoundError: No module named 'familytree' I haven't strayed from the defaults generated along the way, but I'm wondering if I'm missing something in my setup or my file structure that's preventing things from working out of the box. My Django project structure is like this: family-django |-mysite | |-familytree | |-myauth | |-mysite | |-asgi.py | |-settings.py | |-urls.py | |-wsgi.py |-Procfile |-requirements.txt wsgi.py and asgi.py were both created at the start of the project. (Not sure if it's wrong to have both?). wsgi.py has: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() The wsgi file is referenced in settings.py like this: WSGI_APPLICATION = 'mysite.wsgi.application' Now that I'd like to get this up on Heroku, they recommend gunicorn, so I've added a requirements.txt: django django-heroku gunicorn Procfile has: web: gunicorn mysite.wsgi --log-file - I've come across a couple similar posts so far, but each had very particular issues/fixes, and since … -
Django Celery task error while invoked in Post request
I have a below task to run notifications asynchronously @shared_task(name="notifications_task") def notifications_task(activity_type,obj=None, target=None): dispatch_notification_activity(activity_type,obj, target) In the views,py in a post request, I am calling this notfications_task as below notifications_task.delay(UpdateTypeEnum.STOCK_WATCHED, obj=user, target=instance) The Function dispatch_notification_activity takes care of the push notifications, since it takes more Time , I am running it asynchronously getting the below error while calling the notifications_task : kombu.exceptions.EncodeError: Object of type UpdateTypeEnum is not JSON serializable Traceback (most recent call last): File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "E:\stocktalk-api-platform\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "E:\stocktalk-api-platform\apps\stock_watchlist\views.py", line 42, in post notifications_task.delay(UpdateTypeEnum.STOCK_WATCHED, obj=user, target=instance) File "E:\stocktalk-api-platform\venv\lib\site-packages\celery\app\task.py", line 421, in delay return self.apply_async(args, kwargs) File "E:\stocktalk-api-platform\venv\lib\site-packages\celery\app\task.py", line 561, in apply_async return app.send_task( File "E:\stocktalk-api-platform\venv\lib\site-packages\celery\app\base.py", line 718, in send_task amqp.send_task_message(P, name, message, **options) File "E:\stocktalk-api-platform\venv\lib\site-packages\celery\app\amqp.py", line 538, in … -
I keep getting core error in Django as a back-end
I'm new with Django, I'm working on a project with Django as back-end and and angular as front-end. I keep having this error while serving Django, please can anyone help me, i tried uninstalling django-cors-headers-3.7.0 and reinstalling it and i still got this error : ``` ModuleNotFoundError: No module named 'corsheaders.middleware.CorsMiddlewaredjango'; 'corsheaders.middleware' is not a package django.core.exceptions.ImproperlyConfigured: WSGI application 'djangoAPI.wsgi.application' could not be loaded; Error importing module. ** -
How to Increment IntegerField on django on button click from template?
How to Increment IntegerField on django on button click from template? I have two buttons on template one for like and other for dislike.I am using different post requests for both of them but get no increase on likes and dislikes. I hope Information is complete. Here is the models.py code class Post(models.Model): Title=models.CharField(max_length=50) slug = models.SlugField(unique=True,null=True,blank=True) Meta_Tags = models.CharField(max_length=200,null=True) Description=models.TextField() Category=models.CharField(max_length=50) Body=RichTextUploadingField() Date=models.DateField(auto_now_add=True) Views=models.IntegerField(default=0,null=True) Likes=models.IntegerField(default=0,null=True) Dis_Likes=models.IntegerField(default=0,null=True) def __str__(self): return self.Title + " | " + str(self.Date) here is the view.py code def blogdetail(request,slug): post=Post.objects.get(slug=slug) post.Views +=1 if request.POST.get('Like'): post.Likes +=1 if request.POST.get('DisLike'): post.Dis_Likes +=1 post.save() context={ 'post':post } return render(request,'blogdetail.html',context) template code is here <div class="submit-reaction p-3 mb-5"> <span class="p-x3 mb-5" style="float:left"> <form action="" method="post"> {% csrf_token %} <button type="submit" name="Like"style="border:none;background:none;"><i class="far fa-3x fa-thumbs-up text-secondary"></i></button> </form> </span> <span class="p-x3 mb-5" style="float:right"> <form action="" method="post"> {% csrf_token %} <button type="submit" name="DisLike"style="border:none;background:none;"> <i class="far fa-3x fa-thumbs-down text-secondary"></i></button> </form> </span> </div> -
How can I extend month in Django
I am trying to add extra month in my expiry_date field in Django, I've done like this import datetime now = datetime.datetime.now() year = now.year day = now.day hour = now.hour minute = now.minute second = now.second def add_expiry(a): month = now.month print('month : ', month) current_month = month+a print('month adding variable : ', current_month) date = f"{year}/{current_month}/{day}" time = f"{hour}:{minute}:{second}" return f"{date} {time}" print(add_expiry(6)) Output : month : 6 month adding variable : 12 2021/12/27 11:54:17 but problem is it will increase only month but what about year how I can handle year please help. -
How to get a user's OAuth2/access token using Django allauth package
I am using django-allauth in my Django application, and my registration process is handled by Twitch, using allauth's Twitch provider. As of now, users can register on the website using Twitch, log out, and later log back in using Twitch with no problem. However, for making requests to some of Twitch API endpoints, I need the user's Twitch access token to be able to make requests on their behalf (such as following a channel, etc.). On a very old github issues page I came upon a question regarding how to access the user's access token and the answer was to query the SocialToken model and find the logged-in user and the desired provider. But in my case my SocialToken model is empty and there are no tokens to be seen there, and I have no clue how to proceed to populate the model and add every new user's access token there, so that I can make requests on their behalf, given I have the correct scope. Is there a way to add every new user's access token in SocialToken model? And is there a way to update the access token using the refresh token? P.S. I'm thinking about having a … -
Django csrf token not refreshed after first login
I have hosted a website at http://cognezic-dev.ap-south-1.elasticbeanstalk.com/login/. On closer inspection, the form has the same csrf token across page refreshes and browsers, which I suspect to be the cause of the issue,this works fine on the local django server.Dont know where this is being cached. I have added CSRF Middleware in the settings.py too. You can use the test credentials as username bismeet and password bis12345 for testing.