Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django find all rows matching 2 columns criteria
Imagine the model Event like this name email A u1@example.org B u1@example.org B u1@example.org C u2@example.org B u3@example.org B u3@example.org A u4@example.org B u4@example.org I would like to find all emails that contains name A and B. In the example ["u1@example.org", "u4@example.org"] Today I'm doing emails = [ e["email"] for e in models.Event.objects.filter(name__in=["A", "B"]) .values("email") .annotate(count=Count("id")) .order_by() .filter(count__gt=1) ] It's not working because I'm also getting duplicates of emails containing only one name (like u3@example.org). -
How I get data from a Input to run a function in Django
i following a django tutorial and i have troubles getting the data from a input in my HTML. This is the code from the tutorial: views.py def buscar(request): if request.GET["prd"]: producto = request.GET["prd"] articulo = Escucha.objects.filter(user__icontains=producto) return render(request, "Producto/resultados_busqueda.html", {"articulo": articulo, "query": producto}) else: mensaje = "Nos has introducido nada" return HttpResponse(mensaje) HTML: <html lang="en"> <head> <title>Busqueda de producto</title> </head> <body> <form action="/buscar/" method="get"> <input type="text" name="prd"> <input type="submit" value="Buscar"> </form> </body> </html> And this is the code I try to run: views.py def suma(request): if request.get["first"]: first = request.GET["Primer"] second = request.GET["Segundo"] variable = first + second return render(request, "resultado.html", {"variable": variable}) else: mensaje = "lo siento" return HttpResponse(mensaje) HTML (pruebas.HTML) <html lang="en"> <head> <title>Document</title> </head> <body> <form action="/pruebas/" method="get"> <input type="text" name="first"> <input type="text" name="second"> <input type="submit" value="suma"> <p>Resultado: {{ variable }}</p> </form> </body> </html> And the problem I get is: AttributeError at /pruebas/ 'WSGIRequest' object has no attribute 'get' Y really don't know what's the problem, for me the two codes are similar. -
How to get rid of redundant requests ord django
class Post(models.Model): cat_post = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True,null=True) top_post = models.ForeignKey(TopicsCategory, on_delete=models.CASCADE, blank=True,null=True) sub_post = models.ForeignKey(SubTopicsCategory, on_delete=models.CASCADE, blank=True,null=True) class CreatePostView(CreateView): model = Post template_name = 'blog/create.html' form_class = CreatePostForm def get_context_data(self, *args, **kwards): print(self.kwargs) context = super(CreatePostView, self).get_context_data(**kwards) context['btn'] = 'Add' return context def form_valid(self, form, *args, **kwargs): if self.kwargs.get('category_slug') and len(self.kwargs) == 1: category = Category.objects.get(slug=self.kwargs['category_slug']) form.instance.cat_post = category return super(CreatePostView, self).form_valid(form) # передача в форму kwargs view def get_form_kwargs(self): kwargs = super(CreatePostView, self).get_form_kwargs() kwargs.update({'view_kwargs': self.kwargs}) return kwargs def get_success_url(self): return reverse('topics_category_list', kwargs={'category_slug': self.kwargs['category_slug'], }) class CreatePostForm(forms.ModelForm): class Meta: model = Post fields = ['name', 'text', 'discussion'] # widgets = { # 'cat_post': forms.HiddenInput(), # } def __init__(self, *args, **kwargs): self.request = kwargs.pop("view_kwargs") super(CreatePostForm, self).__init__(*args, **kwargs) def clean_name(self): name = self.cleaned_data['name'] if self.request.get('category_slug') and len(self.request) == 1: category = Category.objects.get(slug=self.request['category_slug']) unique = Post.objects.filter(slug=slugify(self.cleaned_data['name']), cat_post=category.pk,discussion=False).exists() if unique: raise ValidationError(f'Post is not unique') return name ** I have duplicate sources in db here form_valid and clean_name. How do I pass the form in the view form form_valid class instance that I got from the database to clean_name. There will be posts for 2 models and requests will increase -
Django vacancy calendar issue
I have a problem with my application. I want to add an employee's vacation date in my calendar but when I put the date it only displays the first date (See photo 1). I would like the employee to post every day. In my example I added from Nov 9 to Nov 12. Does anyone have a solution ? ------- Models.p ------- class Conger(models.Model): employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL) Type = models.CharField(max_length=40, null=True) Annee = models.PositiveIntegerField(null=True) Date = models.DateField("Du: (jj/mm/aaaa)", auto_now_add=False, auto_now=False, blank=True, null=True) Date2 = models.DateField("Au: (jj/mm/aaaa)", auto_now_add=False, auto_now=False, blank=True, null=True) Raison = models.CharField(max_length=200, null=True) Superviseur = models.CharField(max_length=60, null=True) Approuver = models.BooleanField(default=False) data_created = models.DateTimeField(auto_now_add=True, null=True) @property def get_html_url(self): url = reverse('conger') return f'<a href="{url}"> {self.employe.Prenom, self.employe.Nom} </a>' ------- utils.py ------- class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(Date__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, … -
Unable to see table of database added in Django Admin portal
relation "dms_mydocs" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "dms_mydocs" enter image description here I did 'python manage.py makemigrations and migrate and still get same error -
Django / Python: Sorting QuerySet by field on first instance of foreignkey relation
I have the following 2 models, a Lesson model, that can have multiple start / end dates - each with their own Date model. class Lesson(models.Model): name = models.Charfield() (...) class Date(models.Model): meeting = models.ForeignKey( Lesson, verbose_name="dates", on_delete=models.CASCADE, ) start_date = models.DateTimeField( blank=True, null=True, ) end_date = models.DateTimeField( blank=True, null=True, ) For our project we need to order the Lessons by the start_date of their earliest Date instance. So far example, if I have the following data: MEETING A: DATE_1a: 2022-11-01 --> 2022-11-02 DATE_2a: 2022-12-10 --> 2022-12-11 MEETING B: DATE_1b: 2022-11-03 --> 2022-11-04 DATE_2b: 2022-11-05 --> 2022-11-06 Then the queryset should return [<MEETING A>, <MEETING B>] based on the start_date values of the DATE_1a/b instances. (2022-11-01 is earlier than 2022-11-03, al other Dates are ignored) However, what I thought would be a relatively simply query has proven to be a rather evasive problem. My initial approach of the default order_by method used all Date instances attached to a Meeting (and worse, returned a separate Meeting result for each Date instance) qs.order_by(F("dates__start_date").asc(nulls_first=True)) However -I could not conceive of a query to do what we need to happen. My current working solution is to use a whole bunch of python code to … -
Django displaying a static image through a variable from models that is in a JSON object
I have been trying to display an image using Django in my HTML. Normally do display a static file somebody would do: <img src="{% static 'user_profile_pics/pfp_2.jpg' %}" > This image static file has been stored in the variable picture in my models.py. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) picture = models.TextField(max_length=500) The user selects the image they want to choose as their profile image. The views.py file is below with the profile definition having the request JSON dictionary with the variable picture being assigned to the model profile.picture. @login_required def profile(request): profile = Profile.objects.get(user = request.user) return render (request, "profile.html", {"userinfo": {'bio': profile.bio, 'picture': profile.picture}}) def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] confirm_password = request.POST['confirm_password'] bio = request.POST['bio'] picture = request.POST['picture'] if password==confirm_password: if User.objects.filter(username=username).exists(): messages.info(request, 'Username is already taken') return redirect(register) elif User.objects.filter(email=email).exists(): messages.info(request, 'Email is already taken') return redirect(register) else: user = User.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name) user.save() profile = Profile(bio=bio, picture=picture, user=user) profile.save() return redirect('login_user') else: messages.info(request, 'Both passwords are not matching') return redirect(register) else: return render(request, 'registration.html') Next up, displaying the bio and picture within the profile html … -
How to include the JSON Schema definition of a JSONField inside the OpenAPI schema generated by drf-spectacular?
By default, when using drf-spectacular to generate the OpenAPI schema, the JSONField will be typed as object or array. However, I have a JSON Field which is validated against a JSON Schema and I'd like this JSON Schema to be included on the OpenAPI schema. I couldn't find this specific scenario described on the docs of drf-spectacular, but however, I tried modifying it using @extend_schema but with no success. The model looks like this: Car(models.Model): name = models.CharField() data = models.JSONField("Car Data", validators=[JSONSchemaValidator(limit_value=my_schema)]) On the generated OpenAPI schema, this is represented as: data: type: object additionalProperties: {} nullable: true title: Car Data I'm not including a sample on how it should look because I'm seeking answers where this is possible in some pre-defined way. -
base.html only showing the context data in the home page
I have a ListView for my homepage that displays extra data using the get_context_data method. It works, but only in the url of the HomeView, the homepage, not in other templates after I extend the base.html file. Everything else in base appears, the only thing that doesn't is the context data. HomeView class HomeView(ListView): model = Product context_object_name='products' template_name = 'main/home.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) news = News.objects.all() ... context.update({ 'news' : news, ... }) return context base.html {% load static %} <body> <div class="navbar"> <a id="title" href="{% url 'home' %}">home</a> </div> ... <div class="side-bar"> <div class="article"> <h3>News</h3> {% for new in news %} <p>{{ new.title }}</p> {% endfor %} <a href="{% url 'news' %}"><p>See more</p></a> </div> </div> {% block content %}{% endblock %} ... </body> home.html {% extends 'main/base.html' %} {% block content %} <div> {% for product in products %} <p>Some text..</p> {% endfor %} {% endblock content %} Does this mean that I have to add a get_context_data method to every single view I have? Isn't that too repetitive and hard to change? -
Django models relation
The idea is that there are two models: Group and Player. My objective is that there are different Groups and each group has players. Each player can belong to one or more groups. Inside a group, each player has some points accumulated, but the same player can have different points accumulated in another group. class Player(models.Model): username = models.CharField(max_length = 200) won_games = models.IntegerField(default=0) class Point(models.Model): player = models.ForeignKey(Player, on_delete=models.PROTECT, related_name='points') val = models.IntegerField() group = models.ForeignKey(Group, on_delete=models.PROTECT, related_name='points') class Group(models.Model): id = models.CharField(max_length = 200) players = models.ManyToManyField(Player,related_name="groups") points = models.ManyToManyField(Point) I am confused because I don't know how to make that a player has "x" points in group A (for example) and also has "y" points in group B. I want to be able to show the data of a group, for each group, show its members and their points. -
Django with docker compose can not open file '/code/manage.py
i am deploying to docker compose django with postgrest but the problem i have is when trying to deploy an app to django as i get the following output. [+] Running 1/0 ⠿ Container proyecto-db-1 Running 0.0s python: can't open file '/code/manage.py': [Errno 2] No such file or directory asterisk@localhost:~/Documentos/Programacion/django/Proyecto> I get this output by implementing the following code: docker compose run web python manage.py startapp aplicacion docker compose run web django-admin startproject proyecto the docker-compose.yml is: version: '3.9' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" environment: - POSTGRES_NAME=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db The Dockerfile is: # syntax=docker/dockerfile:1 FROM python:3 ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ requirements.txt: Django>=3.0,<4.0 djangorestframework==3.13.1 psycopg2>=2.8 and .env is: ## do not put this file under version control! SECRET_KEY='c_r-e8v1divj8y+hu@-w=n#$xj#ciuejybd3_(k2h789(mcv8$' DEBUG=False ## Super-User Credentials SUPER_USER_NAME = 'root' SUPER_USER_PASSWORD = 'root' SUPER_USER_EMAIL = 'admin@email.com' -
Setting an initial value of an extra field on a ModelForm from an UpdateView
I have a form which is a modelform with two extra fields. In my model, it includes a PointField which is made up of an easting and northing (the X & Y components of the Point). On my modelform, I do not display the PointField and instead display two DecimalFields for the easting and northing: class QuoteForm(forms.ModelForm): easting = forms.DecimalField() northing = forms.DecimalField() class Meta: model = Quote fields = ('desc', 'client', 'contact', 'amount', 'easting', 'northing', 'note') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['note'].required = True self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Save Quote') ) For my CreateView I include a form_valid that takes the easting and northing and turns them into a point and updates the PointField record. For my UpdateView, I want to go backwards from the PointField and populate the Easting and Northing DecimalFields on my form. I am stuck on how to "pass" this information to my form. I tried a get_form in my UpdateView like this, but it fails: class QuoteUpdateView(PermissionRequiredMixin, UpdateView): permission_required = 'jobs.update_quote' redirect_field_name = 'dashboard' model = Quote form_class = QuoteForm template_name = "jobs/quote_form.html" template_name_suffix = '_form' def get_form(self, form_class=None): form = super().get_form(form_class) quote = self.object pt = quote.ptgeom pt.transform(2953) form.fields['easting'] … -
How do I redirect to the created page after I submitted the form Django
I'm trying to redirect to the created page after I've filled out and submitted a form. I have gotten it to work on the update form but not the create form. How do i do this? Here's what I have so far. Let me know if you need more details and code views.py @login_required(login_url='login') def createRoom(request): form = RoomForm() topics = Topic.objects.all() if request.method == 'POST': topic_name = request.POST.get('topic') topic, created = Topic.objects.get_or_create(name=topic_name) Room.objects.create( host=request.user, topic=topic, name=request.POST.get('name'), assigned=request.user, status=request.POST.get('status'), priority=request.POST.get('priority'), type=request.POST.get('type'), description=request.POST.get('description'), ) return render('room', pk=room.id) context = {'form': form, 'topics': topics, 'room': room} return render(request, 'room/room_form.html', context) But this throws this error traceback Traceback (most recent call last): File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\mikha\issue_env\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\mikha\issue_env\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\Users\mikha\issuetracker\base\views.py", line 68, in createRoom return render('room', pk=room.id) Exception Type: AttributeError at /create-room/ Exception Value: 'function' object has no attribute 'id' -
Join two queryset in Django ORM
I'm writing a view that returns this: [ { "field_id" : 1, "stock" : [ { "size" : "M", "total" : 3 } ], "reserved" : [ { "size" : "M", "total" : 1 } ] }, { "field_id" : 2, "stock" : [ { "size" : "M", "total" : 2 }, { "size" : "PP", "total" : 2 } ], "reserved" : [ { "size" : "PP", "total" : 1 }, { "size" : "M", "total" : 2 } ] } ] For this result, I used values and annotation(django orm): reserved = Reserved.objects.all().values("size").annotate(total=Count("size")).order_by("total") stock = Stock.objects.filter(amount=0).values('size').annotate(total=Count('size')).order_by('total')) It's ok for me, but I would like put the reserved queryset inside stock. Like this: [ { "field_id" : 1, "stock" : [ { "size" : "M", "total" : 3, "reserved": 1 } ], }, { "field_id" : 2, "stock" : [ { "size" : "M", "total" : 2, "reserved": 1 }, { "size" : "PP", "total" : 2, "reserved": 0 } ], } ] It's possibile? Reserved and Stock doesn't relationship. -
AAC/ADTS to WAV in Flutter/Django
My Team and I are building a speech-to-text application for a specific purpose. The frontend is in Flutter and the backend is in Django I am using the flutter_sound package for Flutter and the only Codec it supports for recording audio is Codec.aacADTS and I am able to save the file using .aac or .adts On the backend (Django), we're using the Speech Recognition Library and when using the .aac or .adts file with this, it gives an error: ValueError("Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format") We tried using another .wav file and speech recognition works. So, do I need to convert the .aac/.adts file to a .wav file? How should I do it, and should it be on the frontend or the backend? Any library/code snippets to help me with that? Frontend Code (Flutter) Future startRecord() async { setState(() { isRecording = true; }); Directory? dir = await getExternalStorageDirectory(); await recorder.startRecorder( toFile: "${dir!.path}/audio.aac", codec: Codec.aacADTS); } Future stopRecorder() async { final filePath = await recorder.stopRecorder(); final file = File(filePath!); uploadAudio(file); print('Recorded file path: $filePath'); setState(() { isRecording = false; audioFile = file; }); } … -
django - different save methods for user actions and admin action
I have some items connected to users. When every item is added, timestamp is created through inheritance of BaseModel on auto_now field. By mistake when i added new field and populated i updated timestamps. I resolved timestamps with some custom migrations and copy data methods in django. What i wonder - is there possibility to override save method on admin to do only update_fields (so in other words with that i would not update update_at timestamp), while on user actions i want to retain original django save method which would update timestamp. So basically is it possible to have two different save methods? I know that i can override save method - but i don't know if i can have two save methods at the same time. -
How to bind field in django model and celery worker result
The question is theoretical and I just want to understand in which direction to move. I have the model below. The user fills in the form (word, translation) and at the moment the form is saved, celery worker is launched to create an mp3 file of the "word" field. How to link created mp3 file and Word model? How to organize the storage of these files? Thank you very much for your attention. class Word(models.Model): word = models.CharField(max_length=50) translate = models.CharField(max_length=50) audio = models.FileField(upload_to='uploads/') def save(self, *args, **kwargs): #start the celery worker to generate mp3 self.word = self.word.lower() super().save(*args, **kwargs) How to link created mp3 file and Word model? How to organize the storage of these files? -
comparing two (same) functions with same id <function ... at 0x7f490f225900> returns False in Django Middleware
I've created a middleware that modifies one argument for a view in process_view method. As this should do that to one particular view only, I'm comparing callback argument with the view function like this: from third_party_app import view_func class ModifyCodeKwargForViewFuncMiddleware(MiddlewareMixin): def process_view(self, request, callback, callback_args, callback_kwargs): if callback is view_func: raw_code = callback_kwargs["code"] normalized_code = utils.normalize_code(raw_code) return view_func(request, normalized_code) return None This works correctly on my development server; callback is view_func is True But it doesn't work on the server on heroku. I've logged callback and view_func right before comparing it and I noticed that their identifiers are the same (also on the heroku server), which is even weirder: class ModifyCodeKwargForViewFuncMiddleware(MiddlewareMixin): def process_view(self, request, callback, callback_args, callback_kwargs): logging.warning(f"callback is `{callback}`") logging.warning(f"imported view_func is `{view_func}`") logging.warning(f"callback is view_func {callback is view_func}") if callback is view_func: raw_code = callback_kwargs["code"] normalized_code = utils.normalize_code(raw_code) return view_func(request, normalized_code) return None The log entries look like this: callback is `<function view_func at 0x7f490f225900>` imported view_func is `<function view_func at 0x7f490f225900>` callback is view_func False How is this possible and how can I make it work? -
Where does the smartselect URLS belong?
I'm trying to set op SmartSelect in my django project so I can chain dropdown menu's. I do not understand how/where the urls belongs for the installation? urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^chaining/', include('smart_selects.urls')), ) This is what their official installation guide says. Though this is either and old version of Django or i'm doing something wrong as I have not seen any URLS file written this way before and VScode does not recognize it. What am I doing wrong? -
ModuleNotFoundError: No module named 'Authentication.apps' ( Only On Hosting)
All my Django apps are working perfectly on a local server, and when I host it and build it every other app/Module is being found except for Authentications.apps List of Installed Apps INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Appointments.apps.AppointmentsConfig', 'Chattings.apps.ChattingsConfig', 'Finance.apps.FinanceConfig', 'Authentication.apps.AuthenticationConfig', 'Feedbacks.apps.FeedbacksConfig', 'Inventory.apps.InventoryConfig', 'Settings.apps.SettingsConfig', 'rest_framework', 'corsheaders', 'fcm_django', 'cloudinary_storage', 'cloudinary', ] All other apps e.g. Appointments.apps, Chattings.apps, Inventory.apps are being loaded and all of them are on the same directory level. And the thing to be noted is that the same code/app is working on local env If I remove the Authentication.apps part then the app is getting hosted perfectly [2022-11-29 19:24:54 +0000] [1] [INFO] Starting gunicorn 20.1.0 [2022-11-29 19:24:54 +0000] [1] [INFO] Listening at: http://0.0.0.0:8080 (1) [2022-11-29 19:24:54 +0000] [1] [INFO] Using worker: sync [2022-11-29 19:24:54 +0000] [16] [INFO] Booting worker with pid: 16 BASE_DIR in this APP = /workspace/DigiLabBackEnd [2022-11-29 19:25:00 +0000] [16] [ERROR] Exception in worker process Traceback (most recent call last): File "/workspace/.heroku/python/lib/python3.10/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/workspace/.heroku/python/lib/python3.10/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/workspace/.heroku/python/lib/python3.10/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/workspace/.heroku/python/lib/python3.10/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/workspace/.heroku/python/lib/python3.10/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File … -
Assign a verbose_name in django admin
Is there any way to change verbose_name of a field in django admin ? For example, I have a Model A with field example_1. In django admin I want to associate any verbose_name to this field class ModelA(models.Model): example_1 = models.CharField(max_length=50, verbose_name='foo') -
Cannot connect .js files with html files in django
I am unable to connect my index.js file with Django and index.html Django is connected to index.html fine but not to index.js. I have attached my settings.py, urls.py, index.html, webpack.config.js, and index.js files below. settings.py: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent STATICFILES_DIR = os.path.join(BASE_DIR, 'static') TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.1/howto/static-files/ STATIC_URL = 'static/' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [STATICFILES_DIR,TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] In settings.py DEBUG=True urls.py: from django.contrib import admin from django.urls import path from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('hello/', TemplateView.as_view(template_name='index.html')) ] index.html: {% load static %} <!doctype html> <html> <head> <title>NEPTUNE Analytics</title> </head> <body> <script src="{% static 'index-bundle.js' %}"></script> </body> </html> webpack.config.js: const path = require('path'); module.exports = { entry: './js/index.js', // path to our input file output: { path: path.resolve(__dirname, './static'), // path to our Django static directory filename: 'index-bundle.js', // output bundle file name }, }; index.js: function component() { const element = document.createElement('div'); element.innerHTML = 'Hello World'; return element; } document.body.appendChild(component()) I have tried changing DIRS in settings.py … -
Django project on AWS not updating code after git pull
stackoverflowers. I am a Django newbie and I am having an issue. It's my first time ever deploying a Django project on AWS. I am running Postgres, Redis, Nginx as well as my project on Docker there. So everything is working fine, but when I change something on my local machine, push changes to git and then pull them on the AWS instance, the code is not refreshing at all. Only the static files are updating automatically (I guess because of Nginx). Here is my docker-compose config: version: '3.9' services: redis: image: redis command: redis-server ports: - "6379:6379" postgres: image: postgres environment: - POSTGRES_USER= - POSTGRES_PASSWORD= - POSTGRES_DB= ports: - "5432:5432" web: image: image_name build: . restart: always command: gunicorn project.wsgi:application --bind 0.0.0.0:8000 env_file: - envs/.env.prod ports: - "8000:8000" volumes: - ./staticfiles/:/tmp/project/staticfiles depends_on: - postgres - redis nginx: image: nginx ports: - "80:80" - "443:443" volumes: - ./staticfiles:/home/app/web/staticfiles - ./nginx/conf.d:/etc/nginx/conf.d - ./nginx/logs:/var/log/nginx - ./certbot/www:/var/www/certbot/:ro - ./certbot/conf/:/etc/nginx/ssl/:ro depends_on: - web Can you please tell me what to do? Please keep in mind I really am a newbie so if you would be kind to explain it I would be forever grateful! Thanks in advance! I tried deleting everything from docker and … -
Django model gives "TypeError: Object of type UUID is not JSON serializable" error on object create [closed]
I have created a django model as below : class ProjectHistory(models.Model): uuid = models.UUIDField(default=uuid4, editable=False) history = JSONField(default=dict, blank=True, null=True) version = models.PositiveIntegerField(default=0) sequence = models.PositiveIntegerField(default=0) project = models.ForeignKey(Project, related_name='projecthistory', on_delete=models.CASCADE) def Meta(self): unique_together = ("sequence", "project") def save(self, *args, **kwargs): sequence_list = ProjectHistory.objects.filter(project=self.project) self.sequence = sequence_list.count() + 1 super(ProjectHistory, self).save(*args, **kwargs) When I create the object for ProjectHistory model as below : sequence_list = ProjectHistory.objects.filter(project=project) projecthistory = ProjectHistory.objects.create(project=project, history=old_manifest) I see the following error : [29/Nov/2022 18:40:34] INFO [views.py:30] ProjectManifest GET begin [29/Nov/2022 18:40:34] INFO [views.py:203] Subtitle GET success 8 [29/Nov/2022 18:40:34] INFO [views.py:88] ProjectManifest GET end [29/Nov/2022 18:40:34] "GET /project/6e4f263f-3ed3-472c-8311-9202d29a4c4f/ HTTP/1.1" 200 8281 [29/Nov/2022 18:40:39] INFO [views.py:97] ProjectManifest POST begin: 6e4f263f-3ed3-472c-8311-9202d29a4c4f USER DATA : None [29/Nov/2022 18:40:39] INFO [views.py:133] ProjectManifest POST get project [29/Nov/2022 18:40:39] INFO [views.py:143] Project POST has a workspace : 119d535e-1bb0-4e95-b946-4d3ac4d16e0f but no workspacemember [29/Nov/2022 18:40:39] INFO [views.py:147] False - Workspace object (2) - None - None The history : {'fps': 24, 'text': {}, 'asset': {}, 'title': 'Your Video - 6e4f263f3ed3472c83119202d29a4c4f', 'width': 1080, 'height': 1920, 'images': {}, 'videos': {}, 'effects': {}, 'filters': {'preset': ''}, 'version': 1.0, 'bg_color': '00000000', 'duration': 0, 'elements': {}, 'subtitles': {}, 'user_uuid': None, 'audio_only': False, 'created_at': '2022-11-29 16:24:06', 'updated_at': '2022-11-29 16:24:06', 'subtitle_url': … -
Celery 4.4 + Redis - long ETA tasks, default_timeout
We are using Celery (celery==4.4.7) along with Redis broker We have some long ETA tasks with some tasks having ETA of now + 7 days. We were getting issues of the celery tasks being executed multiple times and during debugging we found that the reason is because default_timeout is 1 hour I looked here: celery tasks with long eta (8+ hours) are executed multiple times in a row when eta is reached and https://docs.celeryq.dev/en/4.4.0/getting-started/brokers/redis.html#visibility-timeout We want to increase the default_timeout to 7 days or a bit longer to 8 days. app.conf.broker_transport_options = {"visibility_timeout": 864000} Are there any negative consequences of doing this?