Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
i can't get the background image .please solve the issue
here are some files from project hope so they help you to fix this error. my setting.py """ Django settings for advice_lancing project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(71f#n^0en3u1=j=%bthg1m%d2=so=3+@p6=2u+5k)04caf+od' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'markdownx', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'advice_lancing.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [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', ], }, }, ] WSGI_APPLICATION = 'advice_lancing.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', … -
m2m relationship in PostgreSQL
I have two models related through a third: class Order(models.Model): parts = models.ManyToManyField(Part, through='invent.UsedPart') class Part(models.Model): class UsedPart(models.Model): part = models.ForeignKey(Part, on_delete=models.CASCADE) order = models.ForeignKey('mtn.Order', on_delete=models.CASCADE) This schema worked ok in SQLite, but when i tried to migrate it to PostgreSQL i get this error: Running migrations: Applying invent.0002_auto_20200428_1105...Traceback (most recent call last): File "/home/vadim/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.DuplicateColumn: column "order_id" of relation "invent_usedpart" already exists Did I define them wrong way? -
How to change language or customize template "password_reset_confirm"
Im using auth_views.PasswordResetView, when user the user receives the email to reset password, he will see the view "auth_views.PasswordResetCompleteView" this view loads the following template: {% extends 'base.html' %} {% load static %} {% block css %} <link rel="stylesheet" type="text/css" href="{% static 'css/styles.css' %}"> {% endblock %} {% block content %} <br> <br> <br> <br> <br> {% if validlink %} <h3>Change password</h3> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Restablecer</button> </form> {% else %} <p> El link para restablecer tu contraseña es inválido, posiblemente porque ya ha sido utilizado anteriormente. Por favor solicita nuevamente restablecer tu contraseña. </p> <a href="/">Inicio</a> {% endif %} {% endblock %} But the template is in english: ¿Can I change the language of the template? -
When you click on "publish", an error occurs MultiValueDictKeyError at /publish 'secret'
def publish(request): if request.method == 'GET': return render(request, 'publish.html') else: secret = print(request.POST['secret']) name = print(request.POST['name']) text = print(request.POST['text']) publications_date.append({ 'id': len(publications_date), "name": name, "date": datetime.now(), "text": text }) return redirect('/publications') -
Module for model translations in Django
I am trying to find a module that can perform model translations in Django. In the past (very past, I think it was with Django 1.4) I had used django-hvad and it seemed a good choice at this time. Today, I am looking into awesome Django repo in order to choose on of the listed ones, to use in my new project that I build with Django 3. Which one do you think it's the best choice? From a quick look I had, it seems that there is no perfect solution and each of those has its own issues: django-hvad: Last commit was on 18/08/2017 - a looong time ago! Also, it seems to work well for Django < 2.0. For Django 2+, I see lots of issues in the issue tracker. There are some discussions, an effort to make django-hvad2 since 2015 (some of it has been merged into django-hvad) and a recent question: is it dead? but no answer. To me, this seems a dead end, so it's a NO - it's a pity, AFAIR it was very nice back on Django 1.x days. django-klingon: Quick overview seems good, but it hasn't been developed since November 2018 (last … -
Django specific language for each user is not respected
I need to change the default language for each user, but in my case the translation is not applied with the selected language. I store the preferred language for each user and set it as follows: # set default language try: user_language_filter = UserFilters.objects.get(user=request.user, element__iexact='defaultLanguage') user_language = user_language_filter.value.lower() except UserFilters.DoesNotExist: user_language = 'en' if translation.LANGUAGE_SESSION_KEY in request.session: del request.session[translation.LANGUAGE_SESSION_KEY] translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language print(translation.get_language()) Here I retrieve the stored language for the user and if not available, set it to 'en'. print() shows the correct language. In my settings I have: MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', .... LANGUAGES = ( ('en', _('English')), ('fr', _('French')) ) LOCALE_PATHS = ( os.path.join(BASE_DIR, '../locale'), ) makemessages and compilemessages create the files correctly in the given path. In my ListView I have: def get_context_data(self, **kwargs): context = super(CompanyListView, self).get_context_data(**kwargs) context.update({ 'page_title': _('Manage Companies'), }) return context The text to translate is in the locale files and also translated. I also printed the {{ LANGUAGE_CODE }} in the template which shows the correct one. But in the template the page_title is not translated. Every help is appreciated. -
How to return value from custom database lookup based on model value in Django admin list_display?
Searched the internet a lot for this, tried many solutions but didn't get it working. I have these models. models.py class Cadastro(models.Model): id_cadastro = models.AutoField(primary_key=True) categoria_tipo = models.CharField("Categoria", max_length=50, null=True) chave = models.CharField("Chave", max_length=50, null=False, blank=False) valor = models.CharField("Valor", max_length=50, null=False, blank=False) escricao_valor_cadastro = models.TextField("Descrição / Observação", blank=True, null=True) class Meta: verbose_name_plural = "Cadastros" def __str__(self): return self.valor class ClasseCNJ(models.Model): cod_item = models.IntegerField(primary_key=True) tipo_item = models.CharField(max_length=1) nome_item = models.CharField(max_length=100) class Meta: managed = False db_table = 'itens' def __str__(self): return self.nome_item class ElementoAutomacao(models.Model): id_automacao = models.AutoField(primary_key=True) elemento_automacao = models.ForeignKey('Elemento', on_delete=models.CASCADE, verbose_name="#Elemento", related_name='elemento_automacao', blank=False) tipo_item = models.ForeignKey('Cadastro', on_delete=models.SET_NULL, related_name='tipo_item', null=True, blank=True, limit_choices_to={'chave': 'DEST'}, verbose_name="Item Tipo") item_codigo = models.CharField(max_length=10, blank=True, null=True, verbose_name="#Código") class Meta: verbose_name_plural = 'Regras de Automação' def __str__(self): return self.elemento_automacao.nome_elemento def get_item_cnj_desc(self, obj): if obj.tipo_item == "Movimento": descr_cnj = ClasseCNJ.objects.get(pk=obj.item_codigo, tipo_item='M') elif obj.tipo_item == "Classe": descr_cnj = ClasseCNJ.objects.get(pk=obj.item_codigo, tipo_item='C') elif obj.tipo_item == "Assunto": descr_cnj = ClasseCNJ.objects.get(pk=obj.item_codigo, tipo_item='A') else: descr_cnj = " - " return descr_cnj get_item_cnj_desc.short_description = 'Descrição' Cadastro model is a generic table that I store key-value data to populate the many listboxes. ElementoAutomacao has tipo_item field that points to Cadastro, filtering the options, so it can have "Movimento", "Classe" and "Assunto" and item_codigo field that stores a … -
What is the preffered way to store model details in django?
I am trying to develop a django application to help keep track of macro- and micronutrients in my diet. So far, I am super happy with the django documentation. But right now I am stuck on a more conceptual question related to databases and model relationships. My current model for an Ingredient and the associated NutrientProfile looks like this: class Ingredient(models.Model): ingredient_id = models.UUIDField( verbose_name="Ingredient", primary_key=True, default=uuid.uuid4, editable=False, ) name = models.CharField(max_length=300, unique=False) synonyms = models.CharField(max_length=300, blank=True, null=True) category = models.CharField(max_length=300, blank=True, null=True) class NutrientProfile(models.Model): nutrientProfileID = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) # Ingredient the NutrientProfile is associated to ingredient = models.ForeignKey( to="Ingredient", related_name='nutrientProfile', on_delete=models.CASCADE, blank=True, null=True, ) fat_total = models.DecimalField(max_digits=7, decimal_places=4, blank=True, null=True) protein = models.DecimalField(max_digits=7, decimal_places=4, blank=True, null=True) cholesterol = models.DecimalField(max_digits=7, decimal_places=4, blank=True, null=True) ... more nutrients So currently I am able to create Ingredients, and associate them with one or more NutrientProfiles. I did not define this relation as One-to-One, because there may be multiple NutrientProfiles for a single ingredient (multiple data sources). Now the issue: I realized, that I will need some more information on each nutrient, such as the unit, a comment, date added,... So I came up with the following models to include such … -
Prefetch related querying django
I need to filter on a attribute I can't get access to. I think I need to use prefetch related but I can't get the right one. Or maybe it's just impossible what I try to do. So I want to filter my History objects on supplier ID. These are the models: class History(models.Model): date = models.DateTimeField(auto_now=True) license = models.ForeignKey( License, on_delete=models.CASCADE, related_name="license_history_list" ) class License(models.Model): code = models.CharField(max_length=25) order_item = models.ForeignKey( OrderItem, on_delete=models.CASCADE, related_name="licenses" ) class OrderItem(models.Model): order = models.ForeignKey( Order, on_delete=models.CASCADE, related_name="order_items" ) product_type = models.ForeignKey( ContentType, on_delete=models.SET_NULL, blank=True, null=True ) class Order(models.Model): reference = models.CharField(max_length=50) supplier = models.ForeignKey( Supplier, on_delete=models.CASCADE, related_name="orders" ) So this is the structure I need to go: History -> license -> orderitem -> order -> supplier When I use the filter command I can go to license__order_item__order, but not longer to license__order_item__order__supplier, I don't know why? How can I solve this? -
Django create a Post collection table from multiple models
I want to create a model class at my django application that stores all UUIDs (primary keys) of all my post models as I have more than one. I saw this post: Copy Model Object Id From a Model To Another Model In Django And created a model class accordingly, currently only with one model instead of multiple: class Post_Collection(models.Model): id = models.BigAutoField(primary_key=True, editable=False) post_model1 = models.ForeignKey(Post_Model1, on_delete=models.CASCADE) def __str__(self): return self.id @receiver(post_save, sender=Post_Model1) def ensure_post_exists(sender, **kwargs): if kwargs.get('created', False): Post_Collection.objects.get_or_create(post_model1=kwargs.get('instance')) Sadly I'm running into th following issue: TypeError: str returned non-string (type UUID) Now my question is how can I setup a model that can store copies of all my primary keys when using multiple post models as soon as a new post has been created? Why do I need this? In order to have a performant DB access when using e.g. random.sample at views.py to query random post entries it makes more sense to accomplish this from one table instead of multiple each time a page gets loaded for the user and I want to display some proposals the user may also like to see. -
BUG: Cannot create a Meal instance with a FK Store instance in the views.py (Django and Django Rest Framework)
I am doing a delivery API REST usign Django and Django Rest Framework. In the Meal app there is a bug that has been for days and I cannot solve it. I do not know how to fix it. Thanks you in advance. This is the bug shown in postman: { "store": [ "Incorrect type. Expected pk value, received Store." ] } Meal/models/meals.py class Meal(models.Model): '''Meals models.''' store = models.ForeignKey( Store, on_delete=models.CASCADE, ) name = models.CharField(max_length=120) slugname = models.SlugField( unique=True, max_length=120, ) description = models.TextField(max_length=300, blank=True) price = models.DecimalField( 'meal price', max_digits=5, decimal_places=2 ) picture = models.ImageField( 'meal picture', upload_to='meals/pictures/', blank=True, null=True, help_text="Price max up to $999.99" ) # Status is_available = models.BooleanField( 'Meal available in menu', default=True, help_text='Show is the items is available for customers' ) # Stats rating = models.FloatField( default=5.0, help_text="Meal's rating based on client califications" ) Meal/views/meals.py class MealViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): '''Meals view set. ''' serializer_class = MealModelSerializer lookup_field = 'slugname' search_fields = ('slugname', 'name') # Method call every time this MealViewSet is instanced def dispatch(self, request, *args, **kwargs): '''Verify that the store exists. Add the URL input <store_slugname> to the Meal model field store(FK). ''' store_slugname = kwargs['store_slugname'] self.store = get_object_or_404(Store, store_slugname=store_slugname) return … -
TypeError: Object of type '_Serializer' is not JSON serializable
I am newer in Django rest api. My code is bellow: class PatientViewSet(viewsets.ModelViewSet): queryset = Patient.objects.all() serializer_class = PatientSerializer filter_backends = (DjangoFilterBackend, filters.OrderingFilter) filterset_fields = ['id', 'email', 'mobile', 'status', 'type', 'gender'] ordering_fields = ['id', 'name'] def get_queryset(self): queryset = Patient.objects.all() status = self.request.query_params.get('status') name = self.request.query_params.get('name') if not status: queryset = queryset.exclude(status="DELETE") if name: queryset = queryset.filter(name__icontains=name) return queryset def retrieve(self, request, pk=None): queryset = Patient.objects.all() patient = get_object_or_404(queryset, pk=pk) serializer = PatientSerializer(patient) summary = dict() summary['payment'] = list(PatientPayment.objects.filter(patient_id=pk).aggregate(Sum('amount')).values())[0] summary['appointment'] = DoctorAppointment.objects.filter(patient_id=pk).count() d_appoint = DoctorAppointment.objects.filter(patient__id=pk).last() appoint_data = DoctorAppointmentSerializer(d_appoint) summary['last_appointment'] = appoint_data content = {"code": 20000, "data": serializer.data, "summary": summary} return Response(content) Here url is: http://127.0.0.1:8000/api/patients/2/ When I run in postman it getting the error bellow: TypeError at /api/patients/2/ Object of type 'DoctorAppointmentSerializer' is not JSON serializable Here problem with the code snippet: d_appoint = DoctorAppointment.objects.filter(patient__id=pk).last() appoint_data = DoctorAppointmentSerializer(d_appoint) My question is how can I getting my result? DoctorAppointmentSerializer Class: class DoctorAppointmentSerializer(serializers.HyperlinkedModelSerializer): patient = PatientSerializer(read_only=True) patient_id = serializers.IntegerField() doctor = DoctorSerializer(read_only=True) doctor_id = serializers.IntegerField() doc_image = Base64ImageField( allow_null=True, max_length=None, use_url=True, required=False ) doc_file = Base64ImageField( allow_null=True, max_length=None, use_url=True, required=False ) class Meta: model = DoctorAppointment fields = ['id', 'name', 'mobile', 'problem', 'age', 'gender', 'description', 'doctor', 'doctor_id', 'patient', 'patient_id', 'advice', 'doc_image', 'doc_file', … -
How to track click event on auto generated HTML elements in Template via jQuery in Django
I have a view where templates are nested within and the final template has a post with like and comment buttons/anchor tags. The number of posts are not fixed and are populated dynamically and likes and comments are associated to a single post. The last child template retrieves the posts generated. The issue is with the snippet: ---under dynamic loop--- <a href="" class="like" data-catid="{{ post.id }}">Like</a> ---under dynamic loop--- The above snippet is called by jQuery: <script> $('.like').on("click", function (event){ event.preventDefault(); var postid = $(this).attr("data-catid"); alert(postid); $.ajax({ . .some Ajax stuff... . </script> Now the problem is that whenever I click any like of any post, then I receive the alerts as many times as the number of posts. It happened since the number of posts are not certain and are dynamically generated. So for every post I have a generated anchor tag with class 'like'. Please guide as to how to get only the single event upon the exact link clicked by the user. Please refer my previous post if you seek to know the models also: Django Dynamic Object Filtering issue in Template -
Django on GAE and AWS RDS PostgreSQL
Is it possible to use an AWS RDS PostgreSQL database with a Django app hosted on Google App Engine standard (Python 3)? Currently, any code that tries to connect to the RDS database hangs, but I can connect to the RDS database from my machine. -
Django saves wrong time to database
I have the following model: class lockTime(models.Model): timefield = models.DateTimeField() label = models.CharField(max_length=50, primary_key=True) from the django admin page, when I save a lockTime object, with the time 00:00:00, it is saved to my backend database as 04:00:00 I have updated my settings.py timezone and do not get a message saying "you are 4 hours behind server time": LANGUAGE_CODE = 'en-us' TIME_ZONE = 'America/Toronto' USE_I18N = True USE_L10N = True USE_TZ = True -
Not able to send webcam video to template(.html) file using StreamingHttpResponse in Django 2.2
I recently started django and I wanted to see the video from the laptop camera to Django 2.2 based web app. I was successful in viewing the cam video by directly sending response to web using function display_livefeed. Following is my code of views.py of app 'camerafeed' class mycamera(object): def __init__(self): self.frames = cv2.VideoCapture(0) def __del__(self): self.frames.release() def get_jpg_frame(self): is_captured, frame = self.frames.read() retval, jframe = cv2.imencode('.jpg', frame) return jframe.tobytes() def livefeed(): camera_object = mycamera() while True: jframe_bytes = camera_object.get_jpg_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + jframe_bytes + b'\r\n\r\n') @condition(etag_func=None) def display_livefeed(self): return StreamingHttpResponse( livefeed(), content_type='multipart/x-mixed-replace; boundary=frame' ) I used path('monitor/', display_livefeed, name='monitor'), to see the video streaming on http://127.0.0.1:8000/monitor/ and it works perfectly >>Image from the streaming video<< Now I wanted to display on the html template just line it is done here: https://www.pyimagesearch.com/2019/09/02/opencv-stream-video-to-web-browser-html-page/ but this was done by using Flask. But I wanted to do the same using Django and got stuck. Here is the html file from the above link. <html> <head> <title>Pi Video Surveillance</title> </head> <body> <h1>Pi Video Surveillance</h1> <img src="{{ url_for('video_feed') }}"> </body> I tried to do like this using by making this function: def video_feed(request): return StreamingHttpResponse( livefeed(), # Calling livefeed() function content_type='multipart/x-mixed-replace; boundary=frame' ) … -
Pulling API data into Django Template that has <a></a> tags embedded, is there a way of wrapping the text in an HTML tag?
I'm reading a very large API, one of the fields I need, have "a" tags embedded in the item in the dictionary and when I pull it into my template and display it, it shows the "a" tags as text. exp: "Bitcoin uses the <a href="https://www.coingecko.com/en?hashing_algorithm=SHA-256">SHA-256</a> hashing... ...such as <a href="https://www.coingecko.com/en/coins/litecoin">Litecoin</a>, <a href="https://www.coingecko.com/en/coins/peercoin">Peercoin</a>, <a href="https://www.coingecko.com/en/coins/primecoin">Primecoin</a>*" I would like to wrap this in HTML so when it displays on the page it has the actual links rather than the 'a' tags and the URL. What I'm looking to get: "Bitcoin uses the SHA-256 hashing... ...such as Litecoin, Peercoin, Primecoin*" -
How to serialize a JSON field with multiple permissible keys?
I am trying to serialize a json field, with list values. Something like this: { "source_1": ["key_1"]. "source_2": ["key_3", "key_4"] } I am trying to serialize this using nested serializers, stuck in the middle: models.py class ModelA(models.Model): AVAILABLE_SOURCES = [ "source_1", "source_2" ] SOURCE1_KEYS = ["key_1", "key_2"] SOURCE2_KEYS = ["key_3", "key_4"] custom_keys = JSONField() serializers.py class CustomKeySerializer(serializers.Serializer): # TODO: Here I need to check if all the sources and # keys corresponding to them are valid pass class ModelASerializer(serializers.ModelSerializer): custom_keys = CustomKeySerializer() class Meta: model = ModelA fields = ('__all__',) If at all this cannot be done like this, what can be the other possible ways to do this? -
how to store my converted PDF tabular data into csv into database?
I have converted pdf tables data into CSV in my Django projects using Camelot and it automatically stores in my root directory. now how I'm gonna put my CSV data into my MySQL database? I have created my Model as the CSV file row's name. can anyone help to give ideas? ''' def tables_extract(file_name): filename_with_path = '/pdfs/{}'.format(file_name) basename = os.path.basename(filename_with_path) basename_without_ex = os.path.splitext(basename)[0] tables = camelot.read_pdf(filename_with_path, pages="1-end") table= tables[2].df csv = table.to_csv("{}.csv".format(basename_without_ex)) return csv ''' -
Speed up multiple files upload (jQuery POST)
So, I'm trying to upload a large file (size around 2MB) from the browser to my server running Django, through jQuery's $.post(), like so: async function validateFile(fileElement){ let url = "validate_file/"; let data = new FormData(); data.append("input_name", fileElement.name); let file = fileElement.files[0]; data.append(fileElement.name, file); try { let res = await $.post({ url: url, data: data, processData: false, contentType: false }); return res; } catch (err) { console.error("Validation failed = ",err); return false; } } But the file upload seems extremely slow. Chrome's network timeline shows that uploading the file is taking a huge amount of time. chrome network timeline (attached image) Many users from different regions have reported the same issue, so I think the problem lies somewhere other than my network conditions. The user would be uploading multiple such large files, so such a huge delay is unacceptable. Is there some issue with my AJAX request, or are there some ways/libraries to speed up the file upload ? I'm using jQuery v3.4.1 and Django v2.1.5 -
Django Filters Library
Hi everybody I'm trying to use django_filters library to filter through a list of items. Anyway when the user enter the word he wants to filter by, it doesn't show anything. What am I doing wrong? Hope someone could help! Thanks a lot this is the filters.py import django_filters from .models import Info from django_filters import CharFilter class InfoFilter(django_filters.FilterSet): disco = CharFilter(field_name='disco', lookup_expr='icontains') class Meta: model = Info fields = ['band', 'disco'] this is the view.py: class searchesView(TemplateView): template_name = "search/searches.html" def post(self, request, *args, **kwargs): print('FORM POSTED WITH {}'.format(request.POST['srh'])) srch = request.POST.get('srh') if srch: sp = Info.objects.filter(Q(band__icontains=srch) | Q(disco__icontains=srch)) paginator = Paginator(sp, 10) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) myFilter = InfoFilter(request.GET, queryset=sp) sp = myFilter.qs return render(self.request, 'search/searches.html', {'sp':sp, 'page_obj': page_obj, 'myFilter':myFilter }) else: return render(self.request, 'search/searches.html') and last this is the template: {% if sp %} <form method="get"> {{myFilter.form}} <input type="submit" value="FILTER"/> </form> {% for k in sp %} <div class="container_band" id="display"> <div class=album_band> <!-- insert an image --> {%if k.cover%} <img src= "{{k.cover.url}}" width="100%"> {%else%} <img src="{{no}}" width="100%"> {%endif%} </div> <div class="info_band"> <!-- insert table info --> <table> <tr><th colspan=2><h3>{{k.band}}</h3></th></tr> <tr><td> Disco: </td><td> {{k.disco}} </td></tr> <tr><td> Anno: </td><td> {{k.anno}} </td></tr> <tr><td> Etichetta: </td><td> {{k.etichetta_d}} </td></tr> <tr><td> … -
Django admin set value of read only field from external service
I have a model whereby an id to store is generated by an external service, a 'job_id'. On creation, a post request is sent to this external service, and the job_id is sent back. The model is created only if this job_id is received. Within the django admin, this job_id is set to read only, as this will be created by an external service. I have placed the request to the external service in the clean function: def clean(self): if not self.cleaned_data.get('job_id'): response = requests.post(external_service, params=params, data=data) if response.status_code != 200: raise ValidationError(_("external_service unavailable. Please try again")) self.cleaned_data.update({'job_id': self.__extract_job(response)}) However I cannot seem to add the job_id to the cleaned data, I keep getting: NOT NULL constraint failed: external_service.job_id I have also tried self.cleaned_data.setdefault('job_id', self.__extract_job(response)) but I cannot seem to attach the job_id data to the field. -
Cannot filter out logs from the console
I am trying to filter out certain endpoint logs from the console. My settings.py looks like this: def skip_rss_requests(record): if record.args and record.args[0].startswith('GET /api/feed/rss/'): print("HEEERRRRREEEE") return False return True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'skip_rss_requests': { '()': 'django.utils.log.CallbackFilter', 'callback': skip_rss_requests } }, 'formatters': { 'simple': { 'format': '[%(asctime)s] %(levelname)s|%(name)s|%(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'filters': ['skip_rss_requests'], # 'stream': sys.stdout, 'formatter': 'simple' }, However, I am still seeing these logs in my console output despite the condition being met: [2020-04-28 13:31:11] INFO|django.request|GET /api/feed/rss/ [2020-04-28 13:31:13] INFO|django.request|GET /api/feed/rss/ - 200 HEEERRRRREEEE Any ideas as to why these records are still being logged? -
Django deployment to Postgres with AWS
I am having an issue with making migrations to my newly configurated database on amazon server. When running python manage.py makemigrations I get the error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: FATAL: password authentication failed for user "ubuntu" FATAL: password authentication failed for user "ubuntu" I am stucked and being frankly a beginner and I am confused because although I run a virtual ubuntu machine to host my django app, I don't have a "ubuntu" user. Here is my .env file: SECRET_KEY = secretkey.. DEBUG = False NAME = dbexostock USER = pierre PASSWORD = mypassword HOST = hostnameprovidedbyamazonrds settings.py 'default': { 'ENGINE': 'django_tenants.postgresql_backend', 'NAME': config('NAME'), 'USER': config('USER'), 'PASSWORD' : config('PASSWORD'), 'HOST': config('HOST'), 'PORT': '5432', } } and one of my form needs to write in the database such as: engine = create_engine('postgresql://pierre:mypassword@:hostnameprovidedbyamazonrds:5432/dbexostock', connect_args={'options': '-csearch_path={}'.format(dbschema)}) metricsdb = metrics.to_sql('dashboard_metrics', engine, if_exists='replace') I am out of things to verify, I would appreciate any help on the issue -
Creating a new related object from a predefined parent object in a one to many relation in django
Hi I am making a car dealership project in django and I would like to be able to have a functionality of creating a review on a car just like how one can create a comment on a post in a blog app or social site. In my case the parent object is the car and the related object the review. The ideal outcome would be for one to click on review on the car and the web app to know which car i am reviewing. This is what I had tried so far car Models.py from django.db import models from django.urls import reverse from categories.models import Category # Create your models here. class Car(models.Model): image = models.ImageField(upload_to='images/cars/') make = models.CharField(null=False, blank=False, max_length=30) model = models.CharField(null=False, blank=False, max_length=30) year = models.IntegerField(null=False, blank=False) transmission = models.CharField(null=False, blank=False, max_length=30) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.model def get_absolute_url(self): return reverse('car_detail', args=[str(self.id)]) car review models.py from django.db import models from django.urls import reverse from users.models import CustomUser from cars.models import Car # Create your models here. class Review(models.Model): title = models.CharField(max_length=20) description = models.TextField(max_length=160) date_added = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) car = models.ForeignKey(Car, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return …