Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django save metadata -[Errno 2] No such file or directory:
I got a question. I got an issue with the path: [Errno 2] No such file or directory: I've tried with: url = self.image.url image_meta = image.open(url) then in adding the the first part of URL "https://...." + self.image.url I still got the same issue do you have any idea class Picture(models.Model): catego = models.ForeignKey(Catego,on_delete=models.CASCADE,related_name="catego_pictures") user = models.ForeignKey(User, blank=True, null=True,on_delete=models.CASCADE,related_name='user_pictures') image = models.ImageField(upload_to='nutriscore/') latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') date = models.CharField(max_length=100, blank=True) software = models.CharField(max_length=100, blank=True) artist = models.CharField(max_length=100, blank=True) metadata = models.TextField(max_length=1000, blank=True) pictureoption = models.CharField(max_length=20,choices=Pictureoption.choices,default=Pictureoption.HOME,) publishing_date = models.DateField(auto_now_add=True) def save(self, *args, **kwargs): super().save(*args, **kwargs) url = self.image.url full_path = os.listdir(url) image_meta = image.open(full_path) exif = {} for tag, value in image_meta.get_exif().items(): if tag in TAGS: exif[TAGS[tag]] = value if 'DateTime' in exif: self.date = DateTime if 'Software' in exif: self.software = Software if 'Artist' in exif: self.artist = Artist ... self.metadata = exif super().save(*args, **kwargs) def __str__(self): return self.catego.name -
django not uploading files to aws s3 when using javascript
i have a view where the user can upload multiple images and view them before saving using javascript and im using aws s3 to store my static files the view use to work fine when it was only pure python i only had this problem after adding some js functionality to the template this is my model.py: class Image(models.Model): lesson = models.ForeignKey(Lesson, default=None, on_delete=models.CASCADE) title = models.CharField(max_length=200) image = models.FileField(validators=[validate_image_extension]) views = models.IntegerField(null=True,blank=True,default=0) def __str__(self): return self.title this is my add image view.py def add_lesson_image(request,lesson_id): if request.method == 'POST': lesson = Lesson.objects.get(id=lesson_id) title = request.POST.get('title') images = request.FILES.getlist("file[]") allowed = ['.jpg','.png','jpeg'] #list of the allowed images formats valid = [] for img in images: if Path(str(img)).suffix in allowed: #filtering the images by valid formats valid.append(img) else: messages.warning(request, f"l'extension de fichier '{img}' et n'est pas autorisée") for img in valid: #saving images one by one fs = FileSystemStorage() file_path=fs.save(img.name,img) image=Image(lesson=lesson,title=title,image=file_path) image.save() if len(valid) > 0: #checking if the user input has valid images messages.success(request, "Les images a été enregistrées.") else: messages.warning(request, "aucune image ajoutée") return redirect('edit_lesson',lesson_id) return render (request,'lesson/add_lesson_image.html') this the js added to the template to send multiple images in the request and to view, and preview the images and … -
Annotate sum of vote scores to an item in Django
I have a situation, need to count sum of vote scores and annotate that to an item queryset. model: class Vote(models.Model): item = models.ForeignKey( Item, on_delete=models.CASCADE, related_name="votes") user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="votes") score = models.IntegerField() I tried different variations of this but keep failing: all_votes = Vote.objects.filter(item=OuterRef('pk')) Item.objects.annotate(total_score=Sum(Subquery(all_votes.values("score")))) I get this back all the time: ProgrammingError: more than one row returned by a subquery used as an expression -
Django/Gunicorn/Nginx: wrong JS files seems to be served
My project works locally I have deployed my project with Django/Gunicorn/Supervisor in a remote server I have a select button (id = id_patient) with list of options. When user select an option, informations related to this option are displayed using ajax request. But in remote server, informations are not displayed. When I look with my web browser debug tool (see image), it looks like it is not the good js files that is served But in my static folder on server, it is the good js files... // affichage des informations sur le patient sélectionné pour la ré-allocation $("#id_patient").on("click", function (event) { var csrftoken = getCookie('csrftoken'); if ($(this).val() != "") { $.ajax({ type: "POST", url: $("#form_reallocation").data("patient-url"), data: { csrfmiddlewaretoken: csrftoken, 'patient': $(this).val(), }, dataType: 'html', success: function (data) { $("#information_patient").html(data); } }); } else { $("#information_patient").children().remove(); } }); enter image description here to collect the new static files, I have run python manage.py collectstatic and files are collected but I have a warning message that indicate possible duplicate in static files : Found another file with the destination path 'randomization/js/script.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make … -
DRF POST giving NOT NULL constraint failed
In a simple API with Python 3.9, Django 3.1.2 and DRF 3.12.1, got the following models class Movie(models.Model): movieNumber=models.CharField(max_length=10) movieCategory=models.CharField(max_length=20) class MovieWatcher(models.Model): firstName = models.CharField(max_length=20) lastName = models.CharField(max_length=20) middleName = models.CharField(max_length=20) email = models.CharField(max_length=20) phone = models.CharField(max_length=10) class Reservation(models.Model): # This model has the relation with the other two. movie = models.ForeignKey(Movie,on_delete=models.CASCADE) # CASCADE means that when a Movie is deleted, this reservation must also be deleted. movieWatcher = models.OneToOneField(MovieWatcher,on_delete=models.CASCADE) and the following FBV @api_view(['POST']) def save_reservation(request): movie=Movie.objects.get(id=request.data['movieId']) movie_watcher=MovieWatcher() movie_watcher.firstName=request.data['firstName'] movie_watcher.lastName=request.data['lastName'] movie_watcher.middleName=request.data['middleName'] movie_watcher.email=request.data['email'] movie_watcher.phone=request.data['phone'] movie_watcher.save() reservation=Reservation() reservation.movie = movie reservation.movie_watcher = movie_watcher reservation.save() return Response(status=status.HTTP_201_CREATED) To test that endpoint, I created a POST request to http://localhost:8000/saveReservation/ After, clicked in Body. Inside Body, x-www-form-urlencoded. Here I used as keys: movieId, firstName, lastName, middleName, email and phone. As value for the movieId I add an existing movieId created previously and the user does not exist. All things considered, I was hoping to get the Status 201 Created. Yet, I get a Status 500 Internal Server Error and the following error IntegrityError at /saveReservation/ NOT NULL constraint failed: movieApp_reservation.movieWatcher_id in the terminal it's possible to see this Internal Server Error: /saveReservation/ Traceback (most recent call last): File "C:\Users\tiago\Desktop\beyond\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return … -
Django + Mongodb : Subsetting data in the backend/frontend(template)
My django app pulls raw facebook data from a mongodb database (via djongo/pymongo) and run its through a series of internal data pipelines. At my dashboard.html page, I'm displaying some metrics(posts count, likes count etc..) for the past 7days. Everything works fine up to this point. Now I would like to let the user select from a dropdown menu list whether "past 7 days" or "past 14 days" should be displayed. Obs: It seems that I can't simply use QuerySet because the data being displayed needs to be processed in different pipelienes in the backend before rendering. Obs2: As of now I have some duplicated code in my view in order to get "7 days data" and "14 days data". I would like to simplify that. Obs3: Perhaps Ajax could be a way to go (avoid caching delay/page refresh) but I can't figure out a way to implement that. Thank you in advance!! my views.py: @login_required def dashboard(request): # Mongodb connection this_db = DatabaseFb( 'xxxxMyMongodbConnectionxxx', 'mydbname') collection_posts = this_db.collections('fb_posts') collection_comments = this_db.collections('fb_comments') # ####### Past 7 days FB data ################# this_puller_7d = DataPullerFB(collection_posts, collection_comments, past7days) posts_7d = this_puller_7d.posts_data_puller() comments_7d = this_puller_7d.comments_data_puller() this_dataprep_posts = DataPrepPosts(posts_7d) df_posts_7d = this_dataprep_posts.to_timeseries() this_dataprep_comments = DataPrepComments(comments_7d) … -
Azure App Services: Stopping site MYSITE because it failed during startup
I had my Django web app running on the Azure App Services using a single docker container instances. However, I plan to add one more container to run the celery service. Before going to try the compose with celery and Django web app, I first tried using their docker-compose option to run the Django web app before including the compose with celery service. Following is my docker-compose configuration for Azure App Service version: '3.3' services: web: image: azureecr.azurecr.io/image_name:15102020155932 command: gunicorn DjangoProj.wsgi:application --workers=4 --bind 0.0.0.0:8000 --log-level=DEBUG ports: - 8000:8000 However, the only thing that I see in my App Service logs is: 2020-10-16T07:02:31.653Z INFO - Stopping site MYSITE because it failed during startup. 2020-10-16T13:26:20.047Z INFO - Stopping site MYSITE because it failed during startup. 2020-10-16T14:51:07.482Z INFO - Stopping site MYSITE because it failed during startup. 2020-10-16T16:40:49.109Z INFO - Stopping site MYSITE because it failed during startup. 2020-10-16T16:43:05.980Z INFO - Stopping site MYSITE because it failed during startup. I tried the combination of celery and Django app using docker-compose and it seems to be working as expected. Following is the docker-compose file that I am using to run it on local: version: '3' services: web: image: azureecr.azurecr.io/image_name:15102020155932 build: . command: gunicorn DjangoProj.wsgi:application … -
Python Django project - What to include in code repository?
I'd like to know whether I should add below files to the code repository: manage.py requirements.txt Also created the very core of the application that includes settings.py. Should that be added to the repo? And the last one. After creating a project, a whole .idea/ folder was created. It was not included in the .gitignore file template, so how about that? -
Run QuerySet Django without for
I have a query in Django, and I want to apply a match in each register. whatever = Whatever.objects.all() for w in whatever: contador+=getMycoincidenceswhatever(w) getMycoincidenceswhatever is a function where I search some coincidences with other table. def getMycoincidenceswhatever(w) coincidences=Notificationwhatever.objects.filter (Q(field_whatever__in=w.field)).count() return coincidences Is there some way to do it without use bucle for? The problem is that this query is is slowing down my server, because this bucle. -
Python module not found in docker
i'm trying to start my django project with Docker and it works fine until I add any apps. I checked django code itself by running it with PowerShell and it worked fine. This is my Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ ADD . /authenticate authenticate being the app name I use docker-compose build and docker-compose up to launch project and I get following error message: ModuleNotFoundError: No module named 'authenticate' -
Unable to Load Images In Django
I am trying to make a Django Application. Everything is working fine <but I am unable to Render images which are loaded from a Model I am using SQL Lite in my Local server GitHub Link of my Code → https://github.com/lakshyagarg911/Django-stack-query I browsed through Multiple forums but none of them were helpful to me Please help Settings.py ↓ MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Urls.py ↓ urlpatterns += static(settings.MEDIA_ROOT, document_root=settings.MEDIA_ROOT) part of my HTML {% block main_content %} {% for site in sites %} <div> <h1>{{ site.Platform_name }}</h1> <img src="{{site.Platform_Pic.url}}" alt=""> <p>{{ site.desc }}</p> <p><a href={{ site.link_to_site }}> Click here to go to {{ site.Platform_name }} </a></p> </div> {% endfor %} {% endblock %} -
TypeError at /posts/12/tesing/like/ quote_from_bytes() expected bytes
Well i am trying to add like toggle or like button in my project and got this error . How can i fix this error ? view.py class PostLikeToggle(RedirectView): def get_redirect_url(self, *args, **kwargs): slug=self.kwargs.get('slug') print(slug,'slug') pk=self.kwargs.get('pk') print(pk,'pk') obj =get_object_or_404(Post,pk=pk,slug=slug) print(obj,'post') user=self.request.user if user.is_authenticated: if user in obj.likes.all(): obj.likes.remove(user) else: obj.likes.add(user) return redirect(f'/posts/{pk}/{slug}') traceback: Traceback (most recent call last): File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\views\generic\base.py", line 193, in get return HttpResponseRedirect(url) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\http\response.py", line 485, in __init__ self['Location'] = iri_to_uri(redirect_to) File "C:\Users\AHMED\anaconda3\lib\site-packages\django\utils\encoding.py", line 147, in iri_to_uri return quote(iri, safe="/#%[]=:;$&()+,!?*@'~") File "C:\Users\AHMED\anaconda3\lib\urllib\parse.py", line 839, in quote return quote_from_bytes(string, safe) File "C:\Users\AHMED\anaconda3\lib\urllib\parse.py", line 864, in quote_from_bytes raise TypeError("quote_from_bytes() expected bytes") Exception Type: TypeError at /posts/12/tesing/like/ Exception Value: quote_from_bytes() expected bytes if more detail is require than tell me i will update my question with that information. -
serious django issue - shorting django with django template tags
I want to send variable via django templates tags like {% block panel id='myPanelID' %} so that I don't need to write chuck of codes myself to make accordions. <div class="accordion col-lg-6" id="DisplayStudentsClass"> <div class="card mb-4"> <button class="btn btn-link" type="button" data-toggle="collapse" data-target="#display_class" aria-expanded="true" aria-controls="collapseOne" > <div class="card-header" id="StudentsClass"> <h5 class="mb-0">Create Classes</h5> </div> </button> <div id="display_class" class="collapse show" aria-labelledby="StudentsClass" data-parent="#DisplayStudentsClass" > <div class="card-body"> <form method="POST" action="/settings" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label for="classInput">Class or Grade</label> <input type="text" class="form-control" id="classInput" name="classes" aria-describedby="classHelp" placeholder="Example: Kindergarten, 1, 2, 3, etc." /> <small id="classHelp" class="form-text text-muted"> Create the class <strong><em>{{sdata.sname}}</em></strong >has. </small> </div> <button type="submit" role="button" class="btn btn-primary btn-block"> Submit </button> </form> </div> </div> </div> </div> I want to short the upper code via django template tags. The upper code must work like this: {% block panel_header id='myPanelID' %} Create Classes {% endblock %} {% block panel_body id='myPanelID' %} <...BODY> {% endblock %} -
Postgresql database stops reciving data when django runserver is activate
I have a postgres database that recives data each 10 mins, and its been working fine for a while, and now I´m working on a Django proyect that needs to be connected to that database, and I thing the conection its ok since I can query the data, but there is a problem with the data base, at the moment I run python manage.py runserver 0.0.0.0:8100 (it needs to be in that port), the database stops reciving the data and when I stop the server the db can recive the data again, but the data that was supposed to be in while the server was running was lost. Any ideas on how can I solve this? My Django version is 3.1.1 This is how I make the connection to the database in Django: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'Ray', 'USER': 'postgres', 'PASSWORD': 'mypassword', 'HOST': 'the_ip_adress', } } and the script that puts the data in the database makes the connection like this: engine = create_engine('postgresql://postgres:mypassword@the_ip_adress/Ray',poolclass=NullPool) conn = engine.connect() insert_df(df) conn.close() -
I want an extended user(Vendor) to be able to only see his or her products, orders and customers on a dashboard
I've been trying to filter some data so as to get a certain outcome from the parent model to show to the dashboard but nothing has yielded fruit. I get the an error showing Cannot query "the distributors name": Must be "User" instance. Here is the code. The dashboard View def dashboard(request): orders = Order.objects.filter(Distributor__user=request.user.Distributor) customers = Customer.objects.all() total_customers = customers.count() total_orders = orders.count() Completed = orders.filter(status='Completed').count() OnShipping = orders.filter(status='OnShipping').count() context = {'orders': orders, 'customers': customers, 'total_customers': total_customers, 'total_orders': total_orders, 'Completed': Completed, 'OnShipping': OnShipping} return render(request, 'dashboard.html', context) The distributor's user model class User(AbstractUser): is_distributor = models.BooleanField(default=False) is_customer = models.BooleanField(default=False) class Distributor(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='Distributor', primary_key=True) name = models.CharField(max_length=200, null=True) first_name = models.CharField(blank=True, max_length=150) last_name = models.CharField(blank=True, max_length=150) phone = PhoneNumberField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) Tax_compliance_certificate = models.FileField(upload_to='distaxcerts/', null=False, blank=False) profile_pic = models.ImageField(upload_to='profile/', default="profile1.png", null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) till_no = models.CharField(max_length=20, null=True, blank=True) def __str__(self): return self.user.username def user_name(self): return self.user.first_name + ' ' + self.user.last_name + ' [' + self.user.username + '] ' def image_tag(self): return mark_safe('<img src="{}" height="50"/>'.format(self.profile_pic.url)) image_tag.short_description = 'Image' The Product Model class Product(models.Model): delivery = ( ('Daily', 'Daily'), ('Bi-Weekly', 'Bi-Weekly'), ('Weekly', 'Weekly'), ('Monthly', 'Monthly'), ('Quarterly', 'Quarterly'), ('Semi-Annually', 'Semi-Annually'), ('Annually', 'Annually'), … -
Slug for url in django
I cant get my head around this problem. Went to countless sites and question but can't find why it doesn't work. Everything is imported. The error I get after I run the server is: Reverse for 'random_book' with arguments '('',)' not found. 1 pattern(s) tried: ['book/(?P[-a-zA-Z0-9_]+)$'] It highlights this with red from template: {% url 'random_book' random_item.slug %} Models: class Books(models.Model): title=models.CharField(max_length=200) author=models.CharField(max_length=150) description=models.TextField() cover=models.ImageField(upload_to='images/', blank=True) slug=models.SlugField(max_length=100, blank=True, unique=True) genre=models.ManyToManyField(Genres) def save(self, *args, **kwargs): self.slug= slugify(self.title) super().save(*args, **kwargs) def __str__(self): return self.title def get_absolute_url(self): kwargs=self.slug return reverse('random_book', kwargs=kwargs) Views: def random_book(request, slug): cartile=Books.objects.all() random_item=random.choice(cartile) return render(request, 'carti/book.html', context={"random_item": random_item}) Urls: path('book/<slug:slug>', views.random_book, name="random_book"), Template: <a href="{% url 'random_book' random_item.slug %}">{{ random_item.title }}</a> Hope you guys can help me. -
Scipy, Scispacy, Django, Docker Issue
Having issues with scipy and numpy. This code, part of a Django app, runs perfectly when run on my windows 10 system: try: # sparse_load is a scipy.sparse.csr_matrix sparse_load = scipy.sparse.load_npz(cache) logger.info('Got sparse_load') concept_alias_tfidfs = sparse_load.astype(numpy.float32) except: logger.exception('Something went wrong!' ) # code continues here ... It also runs perfectly when running inside a docker container deployed on a Linux server. The issue is that the type conversion (sparse_load.astype(numpy.float32)) crashes my app when running in a docker container deployed on Docker Desktop running on Windows 10. The strange thing is that logger.exception is never executed! I've tried other type conversions with the same result and also tried removing the astype altogether which resulted in another crash further down in the code (again w/o hitting the exception handler placed around that piece of code. Thoughts? -
There has been a 500 error on the Your Platform Name Here servers - Django/Openedx
Kindly help me out. Mistakenly I deleted 'example.com' which was default site using Django administration web interface and there is no other site available.. Now while restarting the server, it ended up with "There has been a 500 error on the Your Platform Name Here servers" . On google i got the solution "updating the SITE_ID property in the /opt/bitnami/apps/edx/edx-platform/lms/envs/common.py file" but it can only work if i have any site configure in Mysql database. So I want to know in which table I have to add data for configuring my site? -
Django web site radio button
I am creatind a django web site in which a user have to select a skill category and then skill or skills in the same category that selected category and skill or skills have to be stored in model with a username which is loged in... How to do That?? -
django migrate raises IntegrityError
We've been working on a django project and just run into a nasty problem with the django ./manage.py migrate command raising django.db.utils.IntegrityError during post-migration. What's interesting is that ./manage.py test works just fine. The test command creates a testing database and runs ./manage.py makemigrations && ./manage.py migrate. This would suggest we've botched something pretty good in our database, but we're having difficulty figuring out what. Here's the full stack trace. Has anyone else bumped into this sort of error? Note: The IntegrityError is caused by the migrate command attempting to insert a new record into the django_content_type table. It is providing the app_label and model column values, but not providing value for the name column which violates the non-null constraint. One other piece of potentially relevant information is that this project has a custom field. Running migrations: No migrations to apply. Running post-migrate handlers for application utils Traceback (most recent call last): File "/home/jim/src/dc/.pyenv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.NotNullViolation: null value in column "name" violates not-null constraint DETAIL: Failing row contains (46, null, utils, testutilsguidfield). The above exception was the direct cause of the following exception: File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, … -
ModuleNotFoundError: No module named 'My-Project'
Running systemctl status gunicorn.service gives me the output: ● gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Fri 2020-10-16 14:46:53 UTC; 4s ago TriggeredBy: ● gunicorn.socket Process: 61433 ExecStart=/home/myname/My-Project/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock My-Project.wsgi:application (code=exited, st> Main PID: 61433 (code=exited, status=3) Oct 16 14:46:53 django-ubuntu-pleasehelpme gunicorn[61446]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load Oct 16 14:46:53 django-ubuntu-pleasehelpme gunicorn[61446]: File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked Oct 16 14:46:53 django-ubuntu-pleasehelpme gunicorn[61446]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed Oct 16 14:46:53 django-ubuntu-pleasehelpme gunicorn[61446]: File "<frozen importlib._bootstrap>", line 1014, in _gcd_import Oct 16 14:46:53 django-ubuntu-pleasehelpme gunicorn[61446]: File "<frozen importlib._bootstrap>", line 991, in _find_and_load Oct 16 14:46:53 django-ubuntu-pleasehelpme gunicorn[61446]: File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked Oct 16 14:46:53 django-ubuntu-pleasehelpme gunicorn[61446]: ModuleNotFoundError: No module named 'My-Project' Oct 16 14:46:53 django-ubuntu-pleasehelpme gunicorn[61446]: [2020-10-16 14:46:53 +0000] [61446] [INFO] Worker exiting (pid: 61446) Oct 16 14:46:53 django-ubuntu-pleasehelpme gunicorn[61433]: [2020-10-16 14:46:53 +0000] [61433] [INFO] Shutting down: Master Oct 16 14:46:53 django-ubuntu-pleasehelpme gunicorn[61433]: [2020-10-16 14:46:53 +0000] [61433] [INFO] Reason: Worker failed to boot. The directories I’m working in are as follows. myapp/ has my requirements.txt file, my env, and another app/ dir. Within myapp/app, I have manage.py and … -
Django Template If does not work as expected
i'm trying to create a HTML drop-down with Django that shows the numbers 1 - 250 in the template and always selects the last selection after reloading the page. For this i use a variable "clea" to get the value with "request.GET.get('clea')" from the url in my "views.py" to pass it as context. To select the value in the drop-dwon I have the following syntax: <label style="color: white;">Amount</label> <select class="browser-default" id="clea"> {% for _ in ''|center:250 %} <script>console.log("{{ forloop.counter }}" == "{{ data.VIEW.clea }}")</script> {% if "{{ forloop.counter }}" == "{{ data.VIEW.clea }}" %} <script>console.log("Worked")</script> <option value={{ forloop.counter }} selected> {{ forloop.counter }} </option> {% else %} <option value={{ forloop.counter }}> {{ forloop.counter }} </option> {% endif %} {% endfor %} <script>console.log("Finished")</script> </select> Everything works except the If Statement from Django Template! In the log you can see that it always logs false, except if forloop.counter and data.VIEW.clea are equal, then its true, as expected. But it will never log "Worked", although it logs "true" in the line above. Does anyone know what this could be? -
Django save severe generated file in s3bucket
I am trying to save my Server generated file in s3bucket: this is example code: from PyPDF2 import PdfFileWriter output = PdfFileWriter() newReport = open( os.path.join( settings.MEDIA_ROOT, "VISION/{}.pdf".format( bill_obj.company, bill_obj.installation_number ), ), "wb", ) output.write(newReport) newReport.close() Currently, my s3bucket is working very well but my server-generated file is not saving s3bucket. DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID=os.getenv("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY=os.getenv("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME=os.getenv("AWS_STORAGE_BUCKET_NAME") AWS_S3_REGION_NAME =os.getenv("AWS_S3_REGION_NAME") As i showed how i saving the PDF in local machine but i want to save this in s3bucket. How can i do it? -
Django annotate field value from another model
I want to annotate MyModel queryset with a value from another History model. My models relations are the following: class Stage(models.Model): name = models.CharField() class History(models.Model): mymodel = models.ForeignKey( MyModel, on_delete=models.CASCADE, ) stage = models.ForeignKey( Stage, on_delete=models.DO_NOTHING ) created_at = models.DateTimeField( auto_now_add=True ) class MyModel(models.Model): id = models.AutoField( primary_key=True, ) ... Approximate operation I'd like to perform in the ViewSet (order_by I need to get the latest stage): class MyModelViewSet(viewsets.ModelViewSet): ... def get_queryset(self): qs = super(MyModelViewSet, self).get_queryset() qs = qs.annotate(last_stage_name=Value( History.objects.filter(mymodel__id=F('id')).order_by('-created_at')[0].stage.name, output_field=CharField())) But I get the same stage for all objects from the first object instead of the latest stage of every object, so the logics of operation is wrong. I suppose I should get rid of History.objects.filter but can't find appropriate solution. -
Page not found (404) add comment
hi i guys i am trying to add comment on my django project but i get 404 error and i dont know why is that here is my code : urls.py re_path(r'(?P<slug>[-\w]+)/' , views.details , name="details"), path('comment/<prId>)' , views.comment , name='comment'), views.py def details(request , slug): pr = get_object_or_404(Product , slug=slug) category = Category.objects.all() id1 = pr.category.id similar = Product.objects.filter(category_id=id1) pr.view = F('view')+1 pr.save() context = { 'products': pr, 'similar' : similar, 'category' : category } return render(request, "prDetails.html" , context) def comment(request, prId): pr = get_object_or_404(Product ,id=prId) pr2 = pr.slug cm = Comment( name=request.POST.get('name', ''), email=request.POST.get('email' , ''), text=request.POST.get('text', ''), products=pr ) cm.save() return HttpResponseRedirect(reverse('details', args=(pr2,))) and here is my error Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/comment/1/ Raised by: main.views.details No Product matches the given query.