Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I query all products with their variation attributes?
I have following database schema: Django models: class Product(models.Model): name = models.CharField(max_length=150) # price and so on class Size(models.Model): value = models.CharField(max_length=20) class Color(models.Model): value = models.CharField(max_length=20) class Variation(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="variations") size = models.ForeignKey(Size, on_delete=models.CASCADE) color = models.ForeignKey(Color, on_delete=models.CASCADE, null=True, blank=True) So I can write: product.variations But I also want to be able to write product.sizes product.colors to get all sizes or colors that this product has in variation table The problem that I'm trying to solve: I have product card list. And each card has options of sizes and colors to choose and to add to their cart. I want to show the user sizes and colors that this particular product has in database to not list all the sizes and colors from database. But variations can have duplicates, for example, consider these combinations: size - 40, color - red size - 42, color - green size - 44, color - red (again) size - 42 (again), - color gray I want to show the user sizes: 40, 42, 44 colors: red, green, gray Now I can show all of them with duplicates like sizes: 40, 42, 44, 42 colors: red, green, red, gray It is … -
Getting OperationalError: (2000, 'Unknown MySQL error') when accessing mysql database using celery and django
I am using celery with my django application. My application works fine with mysql database, but I am getting (2000, 'Unknown MySQL error') when celery tries to access the database. This happens only when I run celery in a container, when I run it in my ubuntu machine, it works fine. This is the error that I am getting: [2022-06-18 13:39:33,717: ERROR/ForkPoolWorker-1] Task taskMonitor.tasks.monitor[7e6696aa-d602-4336-a582-4c719f8d72df] raised unexpected: OperationalError(2000, 'Unknown MySQL error') Traceback (most recent call last): File "/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/.venv/lib/python3.9/site-packages/django/db/backends/mysql/base.py", line 75, in execute return self.cursor.execute(query, args) File "/.venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 206, in execute res = self._query(query) File "/.venv/lib/python3.9/site-packages/MySQLdb/cursors.py", line 319, in _query db.query(q) File "/.venv/lib/python3.9/site-packages/MySQLdb/connections.py", line 254, in query _mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (2000, 'Unknown MySQL error') The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/.venv/lib/python3.9/site-packages/celery/app/trace.py", line 451, in trace_task R = retval = fun(*args, **kwargs) File "/.venv/lib/python3.9/site-packages/celery/app/trace.py", line 734, in __protected_call__ return self.run(*args, **kwargs) File "/app/taskMonitor/tasks.py", line 18, in monitor for obj in objs.iterator(): File "/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 401, in _iterator yield from self._iterable_class( File "/.venv/lib/python3.9/site-packages/django/db/models/query.py", line 57, in __iter__ results = compiler.execute_sql( File "/.venv/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1361, in execute_sql cursor.execute(sql, params) File "/.venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 103, in … -
ModuleNotFoundError: No module named 'rest_framework.simplejwt'
I'm trying to use simplejwt, but am getting a ModuleNotFoundError. Can you see what I'm doing wrong? requirements.txt algoliasearch-django>=2.0,<3.0 django>=4.0.0,<4.1.0 djangorestframework djangorestframework-simplejwt pyyaml requests django-cors-headers black isort settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", # third party api services "algoliasearch_django", # third-party packages "rest_framework", "rest_framework.authtoken", "rest_framework.simplejwt", # internal apps "api", "products", "search", ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.SessionAuthentication", "rest_framework_simplejwt.authentication.JWTAuthentication", "api.authentication.TokenAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticatedOrReadOnly" ], "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE_SIZE": 10} SIMPLE_JWT = { "AUTH_HEADER_TYPES": ["Bearer"], "ACCESS_TOKEN_LIFETIME": datetime.timedelta(seconds=30), "REFRESH_TOKEN_LIFETIME": datetime.timedelta(minutes=1), } Full traceback: python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Users/saulfeliz/Dropbox/macBook/Documents/Learning/drf/.venv/lib/python3.9/site-packages/django/apps/config.py", line 228, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line … -
How do I get the value of a field of a model instance using the instance's pk?
The following line of code correctly prints the id number of the specific model instance that I'm interested in: views.py print(self.kwargs['pk']) Great. But how do I get the value of a field in that model instance? The following is not working, because I think it's returning the default value listed in the model class and not the value in the model instance: instance_fieldname = self.kwargs.get(ModelName.fieldname) Hoping this is a simple fix. Thank you. -
Where is the Django Migrations model?
I wish to make a custom model, which has a foreign key relationship to the django_migrations table. Can this be done? if so, exactly how do I import the django migrations model? -
UndefinedTable: relation "user" does not exist
I am deploying a fresh new Django app on the server. The problem is when I migrate all the apps in the project. I'm getting UndefinedTable: relation "user" does not exist. Things I have done already: removed all the migrations from all the apps created a new database and new migrations and still getting that error. Weird scenarios: After deployment when I run the Django app locally on the server and hit API locally on the server using curl everything is working fine. like user sign up, but when I try to see in the database it is just empty (refer to the screenshot below). it doesn't even show columns for this user table, but for other tables, I can see columns as well. after migrations I am able to create super user but when I tried to login getting 500 error. and Undefined table relation user does not exit. Expection: AUTH_USER_MODEL = 'registration.User' models.py from django.db import models # Create your models here. import uuid from django.db import models from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.base_user import AbstractBaseUser from django.utils import timezone from .managers import CustomUserManager from rest_framework_simplejwt.tokens import RefreshToken AUTH_PROVIDERS = {'facebook': 'facebook', 'google': 'google', 'twitter': 'twitter', 'email': 'email'} … -
Resolving A Django Error on Form: Object has no attribute
Hi I'm trying to create a form that will when used update one model (Command_Node), and at the same time create an instance of another model (EC_NODE) that has a many to one relationship with the Command_Nodes. However when I go onto the update view and submit the form I'm getting the following error any ideas on how I can resolve this error? Thanks for any help you can offer. AttributeError at /website/update/1 'Beacon' object has no attribute 'EC_Node_set' Request Method: POST Request URL: http://127.0.0.1:8000/website/update/1 Django Version: 4.0.4 Exception Type: AttributeError Exception Value: 'Beacon' object has no attribute 'EC_Node_set' This on traceback points to command_form.EC_Node_set.all() # <- not sure with all _ and Maj here Which I can understand. I think my intention here should be clear enough. I want to set an instance of EC_Node to hold the command just put in via the form, and I understand the error. I just don't know how to get around it so that the view/form does what I want. Relevant views.py def update(request, host_id): host_id = Command_Node.objects.get(pk=host_id) form = Command_Form(request.POST or None, instance=host_id) if form.is_valid(): # Original suggestion was command_form = Command_Form.objects.first() command_form = form.cleaned_data['host_id'] command_form.EC_Node_set.all() # <- not sure with … -
While converting html to pdf using xhtml2pdf with django, the page is stuck in loading while I try to return a Http Response, how do I fix it?
While trying to return a named response with the below code so as to generate a pdf file, the browser is stuck loading, any suggestions on how to fix it def GeneratePdf(request): job = Job.objects.get(pk=id) products = Product.objects.all() supplies = job.jobItem.all() template_path = "company/jobDetails.html" context = { "job": job, "status": status, "supplies": supplies, } template = get_template(template_path) html = template.render(context) result = io.BytesIO() #Creating the pdf output = pisa.pisaDocument(io.BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') #output = pisa.CreatePDF(html, dest=response) if not output.err: pdf = HttpResponse(result.getvalue(), content_type='application/pdf') pdf['Content-Disposition'] = 'filename="products_report.pdf"' return pdf But when removing the part of pdf['Content-Disposition'] = 'filename="products_report.pdf"' as the code below the code works and I get a numbered file. def GeneratePdf(request): job = Job.objects.get(pk=id) products = Product.objects.all() supplies = job.jobItem.all() template_path = "company/jobDetails.html" context = { "job": job, "status": status, "supplies": supplies, } template = get_template(template_path) html = template.render(context) result = io.BytesIO() #Creating the pdf output = pisa.pisaDocument(io.BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') #output = pisa.CreatePDF(html, dest=response) if not output.err: pdf = HttpResponse(result.getvalue(), content_type='application/pdf') return pdf Any suggestions? -
django authenticate returns none but works fine in shell
def login_page(request): if request.method=='POST': user_name = request.POST.get('username') user_password = request.POST.get('password') user =authenticate(request,username=user_name,password=user_password) print(user) if user is not None: login(request,user) return redirect('/') else: messages.info(request,'Invalid user name or password') return redirect('/login_page') else: return render(request,'account/login_page.html') This is the code I'm using the authenticate function is returning none even for a valid input. I have tried authenticate in shell for same input and it is returning value as expected, so I don't understand ehy it is not working for values from HTML form. this is how i saved the user user = User.objects.create_user(email=email,first_name = firstname,last_name=lastname, username=username,password=password1) user.save() shell command i used (i have saved this user and using same credentials for authenticate) user_name = 'issue' user_password = '1234a' user =authenticate(request,username=user_name,password=user_password) this returns True on user is not None -
Media Streaming Servers for Django
I and my team are starting a project where in we are building a scalable live streaming platform just like Youtube. We are using Django as the backend framework. Which is the best media streaming library/server that can be used to achieve the result(It should work along the django project)? Previous Attempts : We researched about various media streaming servers and shortlisted the following three(based on our requirements that it should be able to scale up to a commercial level): Ngnix RTMP module https://github.com/arut/nginx-rtmp-module/ Node Media Server https://github.com/illuspas/Node-Media-Server Django Channels https://channels.readthedocs.io/en/stable/ We are struggling to decide which one to use for our project. I have seen a lot of people use Django channels with django to deal with such projects. But one of my teammates had a bad experience with django channels while working on a similar project hence he is advising us not to go with it. Ngnix module is attractive and a really good reputation on github but I didn't understand it well. We are very doubtful of Node Media server, no positive reviews nor negative reviews. Can you please suggest a better option maybe among them or a different one? Thank you! Any suggestions are welcome. -
Why python3 manage.py runserver built-in command also runs my custom commands?
app_name is added INSTALLED_APPS = [] and in my path /app_name/management/commands/custom.py from django.core.management.base import BaseCommand import server class Command(BaseCommand): def handle(self, *args, **kwargs): server.start() i runned python3 manage.py custom.py it runned the code in my server file fine but now when i run : python3 manage.py runserver on the console activity i can see that python3 manage.py custom.py is automatically called within runserver command -
How to update the user profile of a different user if you are logged in as the owner?
Currently, I am logged in as an owner and I want to update the fields of customers in the database. But the form does not update or show the details as a placeholder because the user model has extended the customer model and hence, the customer model does not have its own fields. How do I get the instance of the User of the Customer in the UpdateView?/How do I update the customer? views.py class CustomerUpdateView(OwnerAndLoginRequiredMixin, generic.UpdateView): template_name = "customer_update.html" form_class = CustomerModelForm queryset = Customer.objects.all() def get_success_url(self): return "/customers" models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class User(AbstractUser): is_owner = models.BooleanField(default=True) is_agent = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) forms.py class CustomerModelForm(forms.ModelForm): class Meta: model = User fields = ( 'email', 'username', 'first_name', 'last_name', ) -
Django: Accessing full User information via ManyToMany field
everyone- I'm new to Django and working on my first big project and I'm having trouble with accessing default Django User model information via a ManyToMany relationship. I've spent a great deal of time searching and can't crack it. models.py class Event(models.Model): event_name = models.CharField(max_length=200, null=True, unique=True) #etc... class School(models.Model): user = models.ManyToManyField(User) event = models.ForeignKey(Event, null=True, on_delete=models.PROTECT) #etc... My url contains the id of the Event, so... views.py def schools(request, pk): event = Event.objects.get(id=pk) school = School.objects.filter(event=event) return render(request, 'accounts/schools.html', {'event':event, 'school':school}) template {% for school in school %} <tr> <td>{{school.name}}</td> <td>{{school.user.all}}</td> {% endfor %} On my template, I'm able to use {{school.user.all}} to get me a Queryset displayed with the username of each User, but I want the first_name and last_name and can't see to figure out how to get that.. Thank you for any suggestions. I greatly appreciate your time! -
How to customize the toolbar of Summernote in django admin
I just need the link button of the summernote. How is this toolbar edited? I tried the documentation and felt no proper guiding. -
cant use emojionearea in django
I cant use emojionearea in a simple page in django, i have followed the basics steps, listed in their website: what i have done: 1.downloaded the zip from their github and copied both of these files into css and js folder 2.configure django static settings e.g add to url, add static dir, add url pattern 3.added the script written above. code: {% load static %} <!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>TODO</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <link rel="stylesheet" href="{% static 'css/emojionearea.min.css' %}"> <link rel="stylesheet" href="{% static 'css/main.css' %}"> </head> <body> {% include 'navbar.html' %} {% block content %} {% endblock content %} <script> $(document).ready(function() { $("#mytextarea").emojioneArea(); }) </script> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="{% static 'js/emojionearea.min.js' %}"></script> </body> </html> and this is the form text area i want to add the emoji to: {% csrf_token %} <div class="form-row"> <div class="col-12"> <label for="inputTask">Tweet:</label> <textarea class="form-control" placeholder="Enter Tweet:" name="tweet" id="mytextarea"></textarea> </div> <div class="col-10"> <label for="inputTime">Image:</label> <input type="file" class="form-control" placeholder="select image:" name="images"> </div> <div class="col-2" style="margin-top: 35px;"> <button type="submit" class="btn btn-outline-primary float-right">Add Tweet</button> </div> </div> </form> i have also tried putting textarea … -
Django: How to unable unlogged user get data other users but enable him have his own data linked to his session
I'm working on simple django project. In this project every reuser has his own data collection as usual we do in our projects but I want to enable unlogged users to have his own data linked with particular session. Off course their data are deleted when session expired but this is the cost of not being registered. I want to block possibility for unlogged user to get data of registered users by typing direct url. All tutorials i have found are obout @login_required decorator but it works only for registered users and doesn't let unlogged users to have his own temporary data. Maybe somebady can help my , give my a hint or suggestion where i can find something useful to solve this problem. Thanks for help -
BaseSerializer.__init__() got multiple values for argument 'instance'
I am new to Django so I have used serializer for the CRUD operations,but this error has come here's my function: def updateemp(request,id): Updateemp = EmpModel.objects.get(id=id) form = CRUDSerializer (request.POST,instance=Updateemp) if form.is_valid(): form.save() messages.success(request,'Record Updated Successfully...!:)') return render(request,'Edit.html',{"EmpModel":Updateemp}) can someone tell me the solution? -
Call ajax of `django-restframework` api from template and the server checks who calls this api
I use google auth login in django project with django-oauth-toolkit What I want to do is Call ajax of django-restframework api from template and the server checks who calls this api. For example, I can get if user is login or not {% if user.is_authenticated %} in template. so, I can call the api with the user information like this. var url = "http://localhost/api/check?id={{user.email}}" $.ajax({ method:"get", url:url .... with id query server can understand who calls this request. However in this method,id is written barely, so you can make the fake request. So, I guess I should make some access token or some other key. Is there any general practice for this purpose??? -
Django SystemCheckError: System check identified some issues:
Good day. Creating a project https://github.com/LeonidPrice/advertisementboard with Django REST framework I got the following error when starting the server: (All migrations are done) (board) D:\python_projects\board\board>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Program Files\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "D:\python_projects\board\board\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\python_projects\board\board\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "D:\python_projects\board\board\lib\site-packages\django\core\management\base.py", line 558, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (captcha.recaptcha_test_key_error) RECAPTCHA_PRIVATE_KEY or RECAPTCHA_PUBLIC_KEY is making use of the Google test keys and will not behave as expected in a production environment HINT: Update settings.RECAPTCHA_PRIVATE_KEY and/or settings.RECAPTCHA_PUBLIC_KEY. Alternatively this check can be ignored by adding `SILENCED_SYSTEM_CHECKS = ['captcha.recaptcha_test_key_error']` to your settings file. WARNINGS: main.AdditionalImage: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the MainConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. main.AdvUser: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'. HINT: Configure the DEFAULT_AUTO_FIELD setting or the MainConfig.default_auto_field attribute to point to a … -
Display all User profiles, in Django template, liked by the currently logged-in User (under ManytoMany field)
I built a portal, where members can see other users' profiles and can like them. I want to show a page where the currently logged-in users can see a list of profiles only of the members they liked. The Model has a filed 'liked', where those likes of each member profile are stored: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') company = models.CharField(max_length=500, blank = True) city = models.CharField(max_length=100, blank = True) website = models.URLField(max_length=500, blank = True) liked = models.ManyToManyField(User, related_name='user_liked', blank=True) My views.py, and here I only show all members so on my template I can loop through each member in members... Including 'member.profile' details from the Profile model. @login_required def all_fav_members(request): users = User.objects.all context = {'members':users} return render(request, 'club/all_fav_members.html', context) I've tried many things, both under views.py and my HTML template, but I was not able to loop through all users associated with a specific Profile under the 'liked' field where that user is equal to request.user. I'm new to Django, hence trying multiple things. The outcome usually is I get the whole list of members, not the ones current user liked. One of the not working examples: {% if member.profile.liked.filter(id=request.user.id).exists()%} My template: … -
Django debug toolbar not showing view class name
I am using a django-debug-toolbar==3.4.0 with Django==4.0.5. Everything works except I see this on the debug toolbar: The expected string should be the class name: DashboardView not "backend_base.views.view". Tha class itself is very simple: class DashboardView(LoginRequiredMixin, NavBarMixin, TemplateView): template_name = 'dashboard.html' In the old version of the same project the result was exactly the classname. What am I missing? -
drf_yasg @swagger_auto_schema not showing the required parameters for POST Request
I am using django-yasg to create an api documentation. But no parameters are showing in the documentation to create post request. Following are my codes: After that in swagger api, no parameters are showing for post request to create the event model.py class Events(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) category = models.ForeignKey(EventCategory, on_delete=models.CASCADE) name = models.CharField(max_length=250, null=True) posted_at = models.DateTimeField(null=True, auto_now=True) location = models.CharField(max_length=100, null=True) banner = models.ImageField(default='avatar.jpg', upload_to='Banner_Images') start_date = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) end_date = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) description = models.TextField(max_length=2000, null=True) completed = models.BooleanField(default=False) def __str__(self): return f'{self.name}' class Meta: verbose_name_plural = "Events" serializers.py class EventSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True, many=False) category = EventCategorySerializer(read_only=True, many=False) class Meta: model = Events fields = '__all__' views.py @api_view(['POST']) @permission_classes([IsAuthenticated]) @user_is_organization @swagger_auto_schema( request_body=EventSerializer ) def registerEvent(request): """ To Register an events, you must be an organization """ data = request.data print("==================") print(data) print("==================") try: Event = Events.objects.create( user = request.user, category=EventCategory.objects.get(category=data['category']), name=data['name'], location=data['location'], start_date=data['start_date'], end_date=data['end_date'], description=data['description'], completed=data['completed'], ) serializer = EventSerializer(Event, many=False) Event = Events.objects.get(id=serializer.data['id']) Event.banner = request.FILES.get('banner') Event.save() serializer = EventSerializer(Event, many=False) return Response(serializer.data) except: message = {'detail': 'Event with this content already exists'} return Response(message, status=status.HTTP_400_BAD_REQUEST) -
I Want to get 2 types of Events, that are, Past Events and Future Events from my Events Model in a Debating Society Website made using Django
I have made a Website for the Debating Society of our College using Django. I would like to have 2 types of events Past and Upcoming (Future) according to the date_of_competition, i.e., if the date and time of competition is past current date and time then return it in past events, and if the date and time of competition is in future of the current date and time then return it in future events Here are my views.py file and models.py file for events models.py from django.db import models class Format(models.Model): format_name = models.CharField(max_length=100, null=False, unique=True) def __str__(self): return self.format_name class Organiser(models.Model): organiser_name = models.CharField(max_length=140, null=False, unique=True) def __str__(self): return self.organiser_name class Event(models.Model): banner_image = models.ImageField(upload_to="events") event_name = models.CharField(max_length=150, null=False) organiser_of_event = models.ForeignKey(Organiser, on_delete=models.CASCADE) format_of_event = models.ForeignKey(Format, on_delete=models.CASCADE) date_of_event = models.DateTimeField(auto_now_add=False) registration_fees = models.IntegerField(default=0, help_text="Enter Registration Fees For The Event in Rupees") details = models.TextField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.event_name view.py from django.shortcuts import render from .models import Event # Create your views here. def events(request): context = { 'title': 'Events', 'events': Event.objects.all() } return render(request, 'main/Events.html', context) What logic should be written in order to get both future and past events from my … -
java.lang.ClassNotFoundException: solr.LatLonType when starting solr with a schema from django build_solr_schema
I want to connect a search functionality to Django. I use django-haystack and solr. with a newly created Solr core I get the following error when starting Solr with a new schema.xml generated from python manage.py build_solr_schema Caused by: java.lang.ClassNotFoundException: solr.LatLonType at java.net.URLClassLoader.findClass(URLClassLoader.java:445) ~[?:?] at java.lang.ClassLoader.loadClass(ClassLoader.java:588) ~[?:?] at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:872) ~[?:?] at java.lang.ClassLoader.loadClass(ClassLoader.java:521) ~[?:?] at java.lang.Class.forName0(Native Method) ~[?:?] at java.lang.Class.forName(Class.java:488) ~[?:?] at java.lang.Class.forName(Class.java:467) ~[?:?] at org.apache.solr.core.SolrResourceLoader.findClass(SolrResourceLoader.java:527) ~[?:?] at org.apache.solr.core.SolrResourceLoader.newInstance(SolrResourceLoader.java:604) ~[?:?] at org.apache.solr.core.SolrResourceLoader.newInstance(SolrResourceLoader.java:598) ~[?:?] at org.apache.solr.schema.FieldTypePluginLoader.create(FieldTypePluginLoader.java:74) ~[?:?] at org.apache.solr.schema.FieldTypePluginLoader.create(FieldTypePluginLoader.java:43) ~[?:?] at org.apache.solr.util.plugin.AbstractPluginLoader.load(AbstractPluginLoader.java:144) ~[?:?] at org.apache.solr.schema.IndexSchema.readSchema(IndexSchema.java:531) ~[?:?] at org.apache.solr.schema.IndexSchema.<init>(IndexSchema.java:188) ~[?:?] at org.apache.solr.schema.ManagedIndexSchema.<init>(ManagedIndexSchema.java:119) ~[?:?] at org.apache.solr.schema.ManagedIndexSchemaFactory.create(ManagedIndexSchemaFactory.java:279) ~[?:?] at org.apache.solr.schema.ManagedIndexSchemaFactory.create(ManagedIndexSchemaFactory.java:51) ~[?:?] at org.apache.solr.core.ConfigSetService.createIndexSchema(ConfigSetService.java:342) ~[?:?] at org.apache.solr.core.ConfigSetService.lambda$loadConfigSet$0(ConfigSetService.java:253) ~[?:?] at org.apache.solr.core.ConfigSet.<init>(ConfigSet.java:49) ~[?:?] at org.apache.solr.core.ConfigSetService.loadConfigSet(ConfigSetService.java:249) ~[?:?] at org.apache.solr.core.CoreContainer.createFromDescriptor(CoreContainer.java:1550) ~[?:?] at org.apache.solr.core.CoreContainer.lambda$load$10(CoreContainer.java:950) ~[?:?] how can i fix my schema.xml? apache solr 9.0 django 4.0 -
Stripe payment intent throw invalid integer
I have been trying to generating stripe payment intent but I see this error of invalid Integer Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 472, in thread_handler raise exc_info[1] File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 42, in inner response = await get_response(request) File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 253, in _get_response_async response = await wrapped_callback( File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 435, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/local/lib/python3.8/asyncio/tasks.py", line 455, in wait_for return await fut File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/usr/local/lib/python3.8/site-packages/asgiref/sync.py", line 476, in thread_handler return func(*args, **kwargs) File "/usr/local/lib/python3.8/contextlib.py", line 75, in inner return func(*args, **kwds) File "/usr/local/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/usr/local/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/yacht-away/bookings/views.py", line 94, in post print(payment.create_payment_intent()) File "/yacht-away/bookings/payments.py", line 14, in create_payment_intent payment = stripe.PaymentIntent.create( File "/usr/local/lib/python3.8/site-packages/stripe/api_resources/abstract/createable_api_resource.py", line 22, in create response, api_key = requestor.request("post", url, params, headers) File "/usr/local/lib/python3.8/site-packages/stripe/api_requestor.py", line 122, in request resp = self.interpret_response(rbody, rcode, rheaders) File "/usr/local/lib/python3.8/site-packages/stripe/api_requestor.py", line 399, in interpret_response self.handle_error_response(rbody, rcode, …