Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use the django-filer file selector in a rich text editor?
Django filer is a great remote image file resource manager. I want to modify all projects to django filer to manage server image resources, but I don't know how to choose to use the django filer file selector from a rich text editor? After consulting a lot of materials, I couldn't find a case where a rich text editor can perfectly integrate with django filer. Is it possible that the django filer file selector cannot be used in conjunction with a rich text editor? -
Bulk_create django
Is there a way to dynamically keep progress of the number of instances saved in the database when using bulk_create in django def bulk_create( self, objs, batch_size=None, ignore_conflicts=False, update_conflicts=False, update_fields=None, unique_fields=None, ): -
Error loading ASGI app. Could not import module "ChatApp.asgi".(Render..com)
Source code link : https://github.com/ab-h-i-n/ChatApp_Django The app is working perfectly and loading websockets in localhost. But when i try to deploy it on render.com it showing this error in log. ` Nov 15 10:38:07 AM WARNING: You are using pip version 20.1.1; however, version 23.3.1 is available. Nov 15 10:43:46 AM WARNING: You are using pip version 20.1.1; however, version 23.3.1 is available. Nov 15 10:43:46 AM You should consider upgrading via the '/opt/render/project/src/.venv/bin/python -m pip install --upgrade pip' command. Nov 15 10:43:48 AM ==> Uploading build... Nov 15 10:43:57 AM ==> Build uploaded in 8s Nov 15 10:43:57 AM ==> Build successful 🎉 Nov 15 10:44:00 AM ==> Deploying... Nov 15 10:44:19 AM ==> Using Node version 14.17.0 (default) Nov 15 10:44:19 AM ==> Docs on specifying a Node version: https://render.com/docs/node-version Nov 15 10:44:24 AM ==> Running 'uvicorn ChatApp.asgi:application' Nov 15 10:44:26 AM ERROR: Error loading ASGI app. Could not import module "ChatApp.asgi". my settings.py is : https://github.com/ab-h-i-n/ChatApp_Django/blob/main/ChatApp/ChatApp/settings.py How do i deploy a Django chat app with websocket and channel. or how do i fix this error -
How to build a robust payment subscription pipeline? [closed]
I am building a subscription-based product in Django. The payment processor in this case is Razorpay. I have few doubts regarding the architecture that I have thought. Business Logic: The user subscribes to my platform and a subscription ID is created. I store it in my DB. Each month an automated job needs to adjust the subscription amount for all the subscribed users based on their usage because it's a usage- based model. Proposed Architecture: After researching a bit I wish to use Celery and RabbitMQ. I am already using RabbitMQ for a different service so planning to reuse it. So after the application is deployed, I start the celery worker. A couple of doubts that I have are, Can I add the command to start the Celery worker be a part of the deployment script? The deployment script spins up a bunch of docker containers for different services. Is this a good approach or is there a better way? My biggest concern is what if the job fails? Like what's the best error-handling strategy? I would appreciate any further suggestions on this architecture greatly. -
order queryset by total sum of prices in drf
I use OrderingFilter, i have pizza model connect to pizzaprice model by many to many field, when i ordering by desc or asc i get not the result expected, how can get queryset ordering by sum of prices or first number in prices models.py class Categorie(models.Model): name = models.CharField(max_length=60, default=[0]) def __str__(self) -> str: return self.name class PizzaPrice(models.Model): price = models.DecimalField(max_digits=8, decimal_places=2) def __str__(self) -> str: return str(self.price) class Meta: ordering = ['price'] class PizzaSize(models.Model): size = models.IntegerField() class Meta: ordering = ['size'] def __str__(self) -> str: return str(self.size) class Pizza(models.Model): name = models.CharField(max_length=60) imageUrl = models.CharField(max_length=150) category = models.ForeignKey(Categorie, default=1, on_delete=models.CASCADE) rating = models.IntegerField(choices=PIZZA_RATING, default=1) sizes = models.ManyToManyField(PizzaSize, blank=True, default=[0]) prices = models.ManyToManyField(PizzaPrice, blank=True, default=[0]) def __str__(self) -> str: return self.name serializer.py class PizzaSerializer(serializers.ModelSerializer): category = serializers.CharField(source='category.name') sizes = serializers.SlugRelatedField(many=True, read_only=True, slug_field='size') prices = serializers.SlugRelatedField(many=True, read_only=True, slug_field='price') class Meta: model = Pizza fields = '__all__' views.py class PizzasList(generics.ListAPIView): queryset = Pizza.objects.all() serializer_class = PizzaSerializer pagination_class = PageNumberPagination filter_backends = [DjangoFilterBackend, OrderingFilter] filterset_fields = ['category'] ordering_fields = ['rating', 'name', 'prices'] example of result: ordering by prices I tried many options but nothing helped I started learning Django not very long ago and I don’t know much, I hope you can … -
Djang views and urls connect
-App folder views.py codes. from django.shortcuts import render from django.http import HttpResponse # Create your views here. def MyApp(request): return HttpResponse("HELLO APP") -App folder urls.py codes. from django.urls import path from . import views urlpatterns = [ path('MyApp/', views.MyApp, name='MyApp'), ] -Project folder urls.py codes. from django.contrib import admin from django.urls import path,include urlpatterns = [ path('', include('MyApp.urls')), path("admin/", admin.site.urls), ] http://127.0.0.1:8000 Error. Using the URLconf defined in FirstProject.urls, Django tried these URL patterns, in this order: MyApp/ [name='MyApp'] admin/ The empty path didn’t match any of these. -
Connect Django to MSSQL 2022
i am trying to connect sql server with django using mssql This is the config in settings.py ` DATABASES = { 'default':{ 'ENGINE':'mssql', # Must be "mssql" 'NAME':'WEB', # DB name "test" 'HOST':'localhost\SQLEXPRESS', # <server>\<instance> 'PORT':'', # Keep it blank 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, } } ` and getting this error when makemigrations RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]SQL Server Network Interfaces: Error Locating Server/Instance Specified [xFFFFFFFF]. (-1) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Invalid connection string attribute (0); [08001] [Microsoft][ODBC Driver 17 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (-1)') hope you guy help me, thanks for reading -
Queries too slow on PostegreSQL
I'm currently working on a project, using Django for web development and PostgreSQL as a database. I have noticed that queries on my system are starting to slow down as the amount of data increases. My main table, say Products, has millions of records, and simple queries like product listing are taking longer than I would like. I've already added some indexes to the relevant columns, but I still feel there's room for improvement. Here is my models: class Produto(models.Model): nome = models.CharField(max_length=255) descricao = models.TextField() preco = models.DecimalField(max_digits=10, decimal_places=2) estoque = models.IntegerField() class Pedido(models.Model): produtos = models.ManyToManyField(Produto) data_pedido = models.DateTimeField(auto_now_add=True) And this is the query I'm doing: produtos = Produto.objects.filter(estoque__gt=0).order_by('-preco')[:10] What am I doing wrong? How can I optimize this query? -
images Not Loading in xhtml2pdf with medial_url, Any Solutions? django
I'm encountering a peculiar issue in my Django project involving xhtml2pdf. When I attempt to generate a PDF using xhtml2pdf, the images, which load correctly when viewing the Django page, fail to display in the generated PDF. in my setting: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' my models classReserva(models.model): ImagenCarnet = models.ImageField(upload_to='images/', default='App/carnets/example.jpg') my views.py def DescargarReserva(request, id): reservas =Reserva.objects.filter(idSolicitud=id) Orden=Reserva() data={'reservas':reservas, 'Orden':Orden} pdf_response=genpdf('templatesApp/pdf.html', data) if pdf_response: response = HttpResponse(pdf_response, content_type='application/pdf') #agrecar variable con id como nombre de archivo quizas se usa {} response['Content-Disposition'] = 'attachment; filename="reserva.pdf"' return response return HttpResponse("Error al generar el PDF", status=500) in my template <img src="{{reserva.ImagenCarnet.url}}" style="max-width: 300px; max-height: 200px;" /> I've tried using {{ MEDIA_URL }}{{ reserva.ImagenCarnet.url }}, but it doesn't seem to resolve the issue. The images load correctly when accessing the Django page, but in the PDF generated by xhtml2pdf, they are not displayed. Here are the images illustrating the problem: image in django In djago load correctly with xhtml2pdf does not load correctly src from file Directly from the file (for reference): I'm seeking guidance on how to resolve this discrepancy between image loading in Django and xhtml2pdf. Any insights or suggestions would be greatly appreciated. Feel free to add … -
Django queryset.filter issue with model type pgfields.ArrayField(models.DateField())
I'm trying to filter a queryset by a date range, on the model it is pgfields.ArrayField(models.DateField()) it is stored in the actual table as text[] (ide). This is the specific piece of code that is failing triage_dates = [r.strftime('%Y-%m-%d') for r in list(rrule.rrule( rrule.DAILY, dtstart=parser.parse(range_start), until=parser.parse(range_end) ))] queryset = queryset.filter(triage_dates__overlap=triage_dates) when I print the type of each item in the triage dates list, it is str, I'm getting this error on the query django.db.utils.ProgrammingError: operator does not exist: text[] && date[]. HINT: No operator matches the given name and argument types. You might need to add explicit type casts. I've even tried converting each item to a date as well. I've been all over different AI platforms looking for answers. I'm thinking I might have to convert this over to a plainsql setup but would prefer to use the ORM if possible. I'm wondering if this is some weird bug between a postgres version + django or something. Any insight is welcomed, thank you! -
How to make delay tasks using Zappa with Django?
I am new to Zappa and I have usually used Django with celery in a server. I know that with Zappa I can schedule tasks with a rate, but how can I just execute a task delayed by a desired amount of time that does not have to be periodic? For example, give the user a finite time to buy a product, or to write a review, or to choose spots in a theater... I am also using AWS What I have read is to create a periodic event that executes every minute to check if the desired time have passed and then do the task, but I think that would be overkilling and I would prefer an event driven solution. I simply dont know if that is possible Another option was to create an SQS queue as this: "events": [ { "function": "your_module.process_messages", "event_source": { "arn": "arn:aws:sqs:us-east-1:12341234:your-queue-name-arn", "batch_size": 10, // Max: 10. Use 1 to trigger immediate processing "enabled": true // Default is false } } ] But I dont know how to put arguments, and just call one task I need without having one queue per function. Thanks and sorry if this is a fool question!!! -
How can I avoid re-triggering a django signal?
I have this signal and I want it to not run once it has already checked each instance once, currently it falls into an infinite recursion loop since it triggers itself each time it runs. from django.db.models.signals import ( post_save, ) from django.dispatch import receiver from app.models import ( QuestionForm, Question, ) @receiver(post_save, sender=form) def get_max_score( sender: form, instance: form, **kwargs: dict, ) -> None: forms = form.objects.all() for form in forms.iterator(): total = 0 questions = form.questions.all() for item in questions.iterator(): total += item.points form.set_score(total) form.save() Any help is appreciated, bonus points if the answer is less complex than n^2. Edit: this is the form model itself: class QuestionForm(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) questions = models.ManyToManyField( Question, related_name='questions' ) created_at = models.DateTimeField( auto_now_add=True, editable=False, ) updated_at = models.DateTimeField( auto_now=True, editable=False, ) max_score = models.IntegerField( default=0, ) def __str__(self): return self.name def get_score(self): return self.max_score def set_score(self, score): self.max_score = score -
Django base.html block overwriting
I want to define, and append to blocks defined in the base.html template. Say I have the following template <!DOCTYPE html> <html> <head> <title>My Project</title> {% block append_to_me %}{% endblock %} </head> <body> {% block content %}{% endblock content %} </body> </html> I would then use the following template for my views, my views render some wagtail components, and those components might want to use the append_to_me block. This goes not only for the wagtail blocks, but also for plain django template tags {% extends "base.html" %} {% block content %} <h2>Content for My App</h2> <p>Stuff etc etc.</p> {# I want it to not matter where I use this. #} {% my_custom_tag %} {% endblock content %} Where {% my_custom_tag %} would do something like this: @register.simple_tag(takes_context=True) def my_custom_tag(context): objects = Preload.objects.all() for object in objects: append_to_header_block(object.html) Wagtail block example: class MyBlock(blocks.StructBlock): title = blocks.CharBlock() content = blocks.RichTextBlock() class Meta: template = 'myapp/myblock.html' myapp/myblock.html {% add_to_header IMG "img/my-img.jpeg" %} ... I also want to be able to keep the content of previous calls to the add_to_header function, as to not overwrite the previous content. I just cannot figure out how I would implement this, because there are a few issues: … -
How can properly verify a user is 18 or older in django?
I want to validate whether a user's age (birth_date) is 18+, this is my current code though it isn't working: ... def min_date(): return (date.today() - timedelta(days=6570)) class User(BaseModel, RemovabledModel, AbstractUser): birth_date = models.DateField( verbose_name=_('birth date'), help_text=_('Birth date'), null=True, blank=True, validators=[ MinValueValidator( limit_value=min_date(), message=("User must be 18 or older") ), ] ) This runs and is functional, but I can still set a user's age to today's date without the application throwing any error message like it would with other validators. Edit: In case it is relevant, this is related validator: def min_date(): return (date.today() - timedelta(days=6570)) class SignUpSerializer(serializers.Serializer): birth_date = serializers.DateField( write_only=True, required=True, validators=[ MinValueValidator( limit_value=min_date(), message=("User must be 18 or older") ), ] ) -
I am trying to install python-saml. It is throwing build dependencies error. It does not give specific reason why it is failing
Traceback (most recent call last): File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\cli\base_command.py", line 180, in exc_logging_wrapper status = run_func(*args) ^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\cli\req_command.py", line 245, in wrapper return func(self, options, args) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\commands\install.py", line 377, in run requirement_set = resolver.resolve( ^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 95, in resolve result = self._result = resolver.resolve( ^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 546, in resolve state = resolution.resolve(requirements, max_rounds=max_rounds) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 397, in resolve self._add_to_criteria(self.state.criteria, r, parent=None) File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 173, in _add_to_criteria if not criterion.candidates: ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_vendor\resolvelib\structs.py", line 156, in __bool__ return bool(self._sequence) ^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 155, in __bool__ return any(self) ^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 143, in <genexpr> return (c for c in iterator if id(c) not in self._incompatible_ids) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 44, in _iter_built for version, func in infos: File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 284, in iter_index_candidate_infos result = self._finder.find_best_candidate( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\package_finder.py", line 890, in find_best_candidate candidates = self.find_all_candidates(project_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\package_finder.py", line 831, in find_all_candidates page_candidates = list(page_candidates_it) ^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\sources.py", line 134, in page_candidates yield from self._candidates_from_page(self._link) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\package_finder.py", line 791, in process_project_url index_response = self._link_collector.fetch_response(project_url) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\collector.py", line 461, in fetch_response return _get_index_content(location, session=self.session) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\collector.py", line 364, in _get_index_content resp = _get_simple_response(url, session=session) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\ubhat\Projects\etl\Lib\site-packages\pip\_internal\index\collector.py", line 135, … -
Django Tables2 with TemplateColumn the View is not printing the request
I'm trying to print the request in my view but nothing happens when I click on the 'Editar' button (TemplateColumn), this is what I have in my code: tables.py import django_tables2 as tables from django_tables2 import TemplateColumn from .models import Vencimientos, LogAsistencia class VencimientosTable(tables.Table): asistencia = TemplateColumn( '<a class="btn btn btn-info btn-sm" href="{% url "checkin" record.id %}">Editar</a>') class Meta: model = Vencimientos template_name = "django_tables2/bootstrap5.html" fields = ("cliente","vencimiento","activo" ) attrs = {"class": "table table-hover table-sm"} urls.py urlpatterns = [ .... path('asistencia/<int:pk>/', CheckIn.as_view(), name='checkin') ] views.py class CheckIn(View): def get(self, request): print(request) return redirect ('asistencia') when I click on the "Editar" button in the table the idea is to get the record.id so I can add some extra code, but the button doesn´t do anything UPDATE I inspect the button and I see the link correct: The button doesn´t do anything still -
Django ORM ForeignKey queryset output using annotations
I have the following 3 django models (using some abstractions): class Person(models.Model): full_name = models.CharField(max_length=120, validators=[MinLengthValidator(2)]) birth_date = models.DateField(default='1900-01-01') nationality = models.CharField(max_length=50, default='Unknown') class Meta: abstract = True class Director(Person): years_of_experience = models.SmallIntegerField(validators=[MinValueValidator(0)], default=0) objects = DirectorManager() class Actor(Person): is_awarded = models.BooleanField(default=False) last_updated = models.DateTimeField(auto_now=True) class Movie(models.Model): MOVIE_GENRES = ( ('Action', 'Action'), ('Comedy', 'Comedy'), ('Drama', 'Drama'), ('Other', 'Other') ) title = models.CharField(max_length=150, validators=[MinLengthValidator(5)]) genre = models.CharField(max_length=6, choices=MOVIE_GENRES, default='Other') rating = models.DecimalField(max_digits=3, decimal_places=1, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)], default=0) director = models.ForeignKey(Director, on_delete=models.CASCADE) starring_actor = models.ForeignKey(Actor, on_delete=models.SET_NULL, blank=True, null=True) actors = models.ManyToManyField(Actor, related_name="actors") As you can see in the code above, I have also 1 manager. Here it is: class DirectorManager(models.Manager): def get_directors_by_movies_count(self): return self.all().values("full_name").annotate(movies_num=Count("movie__director")).order_by("-movies_num", "full_name") And here is my problem. I need and output like this: <QuerySet [<Director: Francis Ford Coppola>, <Director: Akira Kurosawa>...> instead, I am receiving this: <QuerySet [{'full_name': 'Francis Ford Coppola', 'movies_num': 2}, {'full_name': 'Akira Kurosawa', 'movies_num': 1}...]> So, I need just one record: Director, not these 2 full_name and movies_num, but i want to preserve the same group and order logic. How to do this? -
is there way to make a foreign key in django readonly and still submit the form without any error?
I have been trying to make a foreign key from my django forms read only , I am creating a web-app with system control, i don't want certain users to edit a submitted field class ApproveForm(forms.ModelForm): def init(self, *args, **kwargs): super(ApproveForm, self).init(*args, **kwargs) # Filter the queryset for the 'category' field to only include active categories self.fields['category'].queryset = Category.objects.filter(status='active') # Filter the queryset for the 'category' field to only include active categories self.fields['location'].queryset = Location.objects.filter(status='active') self.fields['location'].widget.attrs['readonly'] = True class Meta: model = Request fields = ('item','category','location','quantity','comments' ) widgets = { 'item':forms.Select(attrs={ 'class':'form-control', }), 'category':forms.Select(attrs={ 'class':'form-control', }), 'location':forms.Select(attrs={ 'class':'form-control', }), 'quantity':forms.NumberInput(attrs={ 'class':'form-control', 'min':'0', 'readonly':'readonly' }), 'comments': forms.Textarea(attrs={ 'rows':4,'cols':5, 'class':'form-control' }) } it's not working , I have tried using hidden, it hides all the whole values leaving the label on display -
Use Django Action to Populate Database: Show Drop Down Action Menu Even for Empty DB
Using django, I have a startup script that loads static data into the database. Currently I call it via a url, but thought it be nice if it be done from within the admin menu of the respective table. I found the option to use admin actions for this, but allas, they do not show up if the database is empty. Any idea how to still show the admin actions dropdown menu? -
create pivot table using django and pivottable.js
I hope you can help me create pivot tables, the same as the one in the picture from the Odoo program, using django, js and pivot table. enter image description here [enter image description here]) I tried to write some codes but did not reach any results -
SMTP.starttls() got an unexpected keyword argument 'keyfile'
I'm trying to send email with this code: send_mail( subject='Restore password', message='Restore password for ' + email, from_email=os.environ.get('GMAIL_EMAIL', ''), html_message=html_message, recipient_list=[email] ) And having this error SMTP.starttls() got an unexpected keyword argument 'keyfile' My python version is 3.12.0 My Django version is 4.0.1 -
Place bid implementation not working on my django app
I have really tried different methods in order to implement a place bid functionality, but all my efforts were futile. I don't what's wrong with the code. Here's my code: views.py def place_bid(request): if request.method == "POST": #data = json.loads(request.body) #create and save the bid value item_id = request.POST("item_id") listing_item_id = get_object_or_404(Listing, pk=item_id) bid_value = request.POST("bid_value") Bids.objects.create(bidder=request.user, bid_price=bid_value, listing_id=listing_item_id) listing_item_id.initial_price = bid_value listing_item_id.save() return render(request, "auctions/listing_view.html", { "price": listing_item_id, "message": "Your bid has been placed successfully" }) models.py class Listing(models.Model): product_name = models.CharField(max_length=64, verbose_name="product_name") product_description = models.TextField(max_length=200, verbose_name="product description") product_image = models.ImageField(upload_to="images/", verbose_name="image", blank=True) is_active = models.BooleanField(blank=False, default=True) initial_price = models.DecimalField(decimal_places=2, max_digits=6, null=True, blank=True) owner = models.ForeignKey(User, related_name="auction_owner", on_delete=models.CASCADE, default=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category") def __str__(self): return self.product_name class Bids(models.Model): bidder = models.ForeignKey(User, null=True, on_delete=models.CASCADE) bid_price = models.DecimalField(decimal_places=2, max_digits=6, null=True, blank=True) listing_id = models.ForeignKey(Listing, null=True, on_delete=models.CASCADE) def __str__(self): return self.bid_price templates <div class="right"> <h3>{{ listing.product_name }}</h3> <h4>${{ price.initial_price }}</h4> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> <div class="btn-groups"> {% if listing in watchlist_items %} <a href="{% url 'remove_from_watchlist' item_id=listing.id … -
FileNotFoundError: [Errno 2] No such file or directory in celery container while my django application container exists
I am developing a django application in which I have to manipulate excel files. I have two containers: one for my main django application and another for celery where I process my files. These two containers have the same context and share the same environment variables. here is the view where is my problem: def file_recovery(request): reponse = {} request.method == "POST": extensions = ["xls","xlsx"] form = UploadExcelMeterFile(request.POST,request.FILES) if form.is_valid(): excel_file = request.FILES["excel_file"] extension = request.FILES["excel_file"].name.split(".")[-1] if not extension in extensions: ... else: obj_file = XSLFileObjects.objects.create(file=excel_file) # I create an file objects my_task.apply_async(args=[obj_file.id]) # I send the id of that objects to my task to get the file directory ... else: ... else: ... in my_task.py @shared_task def ajouter_compteur_depuis_excel(id): from elec_meter.models import XLSFileObject obj_file = XLSFileObject.objects.get(id=id) file = obj_file.file ... In my task I try to recover the file and do the processing. This file exists in the django app container but does not exist in celery. I receive FileNotFoundError: [Errno 2] No such file or directory When I try to create another object, I notice that the previous file which does not exist appears in celery. docker-compose.yml version: '3' services: app: container_name: ozangue build: context: . command: > python … -
How to generate a user-specific PDF in Django based on user ID?
I'm ivan, a junior-level Computer Science student and aspiring developer. I'm currently delving into web development using Django. As part of my learning journey, I'm working on a project where I need to generate a customized PDF for each user, identified by their unique user ID. My current experience is at the junior trainer level, and while I'm familiar with the basics of Django, I'm struggling a bit with the specific implementation of PDF generation using a particular library. I would like to seek the community's assistance in understanding how the [library name] library works in Django and how I can apply it to create these user-specific PDFs based on user ID. I appreciate any guidance, code examples, or resources that can help me overcome this hurdle.the crud works perfectly the pdf it generates comes out with: No reservations found in the system. views.py from django.http import FileResponse from reportlab.pdfgen import canvas from .pdfGen import genpdf from django.http import HttpResponse from django.shortcuts import render, redirect from .models import Reserva from .forms import ReservaForm def agregarReserva(request): form=ReservaForm() if request.method=='POST': form=ReservaForm(request.POST, request.FILES) if form.is_valid(): form.save() form=ReservaForm() #para que no duplique los datos en la bd return redirect('/') reservas=Reserva.objects.all() data={'form':form,'reservas':reservas} return render(request, 'templatesApp/agregar.html', … -
axiosInstance raise error ->( Invalid token specified) -> after update -> user profile information ? why ? please solve it
in windows 10 , i'm using react-router-dom 5.2.0 and react-redux 7.2.5 and react 17.0.2 and axios 0.21.4 and WebStorm 2023.1.3 IDE. Consider - axiosInstance.js: import jwt_decode from 'jwt-decode'; import dayjs from 'dayjs'; import axios from 'axios'; import { AxiosRequestConfig } from 'axios'; import {updateAccessToken} from '../actions/userActions'; const baseURL = 'http://127.0.0.1:8000'; export const axiosInstance = (userInfo , dispatch) => { const instance = axios.create({ baseURL : baseURL, headers : { 'Content-Type': 'application/json', Authorization:`Bearer ${userInfo?.access}`, } }); instance.interceptors.request.use(async (req)=> { const user = jwt_decode(userInfo.access); const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 5000; if (!(isExpired)) { return req } const response = await axios.post( '/api/v1/users/token/refresh/' , {refresh:userInfo.refresh}, ); dispatch(updateAccessToken(response.data)) req.headers.Authorization = `Bearer ${response.data.access}`; return req; }); return instance } consider - userActions.js - updateUserProfileAction : export const updateUserProfileAction = (user) => async (dispatch, getState) => { try { dispatch({ // USER UPDATE PROFILE REQUEST type: USER_UPDATE_PROFILE_REQUEST, }); const {userLogin: {userInfo}} = getState(); //GET STATE FROM STORE BY KEY `USER_LOGIN` const authRequestAxios = axiosInstance(userInfo,dispatch) const {data} = await authRequestAxios.put('http://127.0.0.1:8000/api/v1/users/profile/update/', user) dispatch({ // USER UPDATE PROFILE SUCCESS type: USER_UPDATE_PROFILE_SUCCESS, payload: data, }); dispatch({ //USER LOGIN SUCCESS type: USER_LOGIN_SUCCESS, payload: data, }); localStorage.setItem('userInfo', JSON.stringify(data)); } catch (error) { dispatch({ // USER UPDATE PROFILE FAILED type: USER_UPDATE_PROFILE_FAILED, payload: error.response …