Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to get the request values using signals, to be able to instantiate a chat object
I'm finishing a college project and I'm stuck on generating notifications whenever a user sends a message to another, I have a notification model, but I'm not able to send the message to the notification in django admin I can already insert the notification and display the screen, but only manually, when the user sends the message, it is not sent to the notification model :'( from django.db import models from django.db.models.signals import post_save, post_delete class Chat(models.Model): codigoSala = models.CharField(max_length=20, unique=True) locador = models.CharField(max_length=50, blank=False, null=False) locatario = models.CharField(max_length=50, blank=False, null=False) nomeSala = models.CharField(max_length=200, blank=True, null=True) def __str__(self): super().__init__() return self.codigoSala def add_chat(self): sender_message = Chat( self.codigoSala, self.locador, self.locatario, self.nomeSala) sender_message.save() class Mensagem(models.Model): texto = models.CharField(max_length=80) chat = models.ForeignKey(Chat, on_delete=models.CASCADE) def __str__(self): return self.texto def add_message(sender, instance, *args, **kwargs): message = instance here I am not able to get this parameter information, as far as I understand, the signals do not allow the request for an argument (in add_message in my case) these values below are passed in the url, I managed to get the values, but I tried in different ways to solve my real problem that I forgot how I did, now that I found a way to … -
how can i display the result of my sqlite query in a html django page
I have the follwing querry set in my views.py with connection.cursor() as cursor: #cursor.execute("SELECT AgentName FROM 'CSQ Agent Report' ") cursor.execute("SELECT 'AgentName', count (*) FROM 'CSQ Agent Report' WHERE 'AgentName' != 'None' AND 'OriginatorDNHANDELED' = '1' or 'OriginatorDNNOTHANDELED' = '1' Group by 'AgentName'") obj = cursor.fetchall() context = { 'object': obj } return render(request,"CSQ/detail.html", context) and i like to display the result of the querry in my html page which code is : {% extends 'base.html' %} {% block content %} <h1> Stats Call Center Of Feb </h1> <p> Nb of calls received by agent </p> <ul> {% for var in object %} <li> {{var}} </li> {% endfor %} </ul> {% endblock %} I have the same querry created in python and it works as expected : cursor.execute(""" SELECT "AgentName", count (*) FROM "CSQ Agent Report" WHERE "AgentName" != "None" AND "OriginatorDNHANDELED" = '1' or "OriginatorDNNOTHANDELED" = '1' Group by "AgentName" """) liste8= cursor.fetchall() for i in range (len(liste8)): print (liste8[i][0],liste8[i][1]) and the result in python is as follow : Agent1 11 Agent2 41 Agent3 249 Agent4 46 Agent5 2 Agent6 216 Agent7 117 Agent8 242 Agent9 50 I would like to display the same resulat in my Html Django … -
django request.user.is_authenticated returns AnonymousUser after a while
I have a very weird problem with Django authentification/Login. I can log in just fine and I'm able to browse a couple of pages with an authenticated and logged-in user until at some point my request.user.is_authenticated returns False. I then have an AnonymousUser and can't access the user information anymore. This problem is not present on my localhost server and only happens when I try out my production server. I would say this problem occurs every 50% of requests, which means I have one chance out of two that my user keeps its authentication after a redirect. The login() function on my home page works fine everytime I use it so it means the problem arise during the redirect. My setup used to work perfectly until I recently tried to implement a Facebook auth with allauth. I had difficulties to get it running and I suspect this might have caused the present issue. I have since removed every line that was related to the facebook login but I still could not get my production server to run. Here is my settings.py AUTH_USER_MODEL = 'custom_user.CustomUser' INSTALLED_APPS = [ 'django.contrib.sites', 'django.contrib.admin.apps.SimpleAdminConfig', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'custom_user.apps.CustomUserConfig', 'user_profile', 'rest_framework', 'django_email_verification', ] … -
How to use model attribute in both POST and GET in Django
I am getting an attribute called Number using POST method. Also I have a form in my template with GET method.For that form,I need to use the Number but it returns None. views.py def recognition(request): tableFilter = '' if request.method == "POST": Number = request.POST.get('Number', None) meter = Meter.objects.get( Number= Number) if request.method == "GET": ************Here I need to use meter existing in POST part(first if)********* object_list = Report.objects.filter(meter=meter) tableFilter = RecordFilter(request.GET, queryset=object_list) context = { 'meter':meter, 'table_filter':tableFilter, } return render(request, 'services/specificMeterDelete.html',context) How can I access Number in GET part? Thanks. -
Django if now = post date in template
I'm a bit lost, In my MySQL DB DateField is saved like that 2020-10-29 In my template I try to see if DateField == Now. In my models it's DateField not a DateTimeField So I've try to do this: {% now "Y-F-j" as current_date %} {% if post.start_date == current_date %} Today{% else %} Ended{% endif %} But even if it should match I got ended everywhere... Do you have any idea? -
Django-admin is not doing anything?
I am trying to create a web app and have installed Django. I have the latest version of it and pip. When I run django-admin startproject mysite, nothing happens. I have installed the path to the bin folder for django on my environment variables and still the commands are being ignored. I can create a virtual environment and still django-admin is being ignored. Is the folder being created in a different file location? Please help I am so lost right now. -
Django template not detecting certain keys while iterating over a dict
I am facing this weird issue: These are three rows of a 'table' passed by view.py as printed out in Django template: {'c2': {'tag_id': 'c2', 'display_id': 'C0002', 'name': 'Financial Statements', 'class': 'child-of-None', 'type': 'category', 'statement': 'N/A', 'jun_20': 0, 'jul_20': 0, 'aug_20': 0}, 'c1': {'tag_id': 'c1', 'display_id': 'C0001', 'name': 'Balance Sheet', 'class': 'child-of-2', 'type': 'category', 'statement': 'N/A', 'jun_20': 0.0, 'jul_20': 0.0, 'aug_20': 0.0}, 'c6': {'tag_id': 'c6', 'display_id': 'C0006', 'name': 'Non-Current Assets', 'class': 'child-of-1', 'type': 'category', 'statement': 'N/A', 'jun_20': 0.0, 'jul_20': 36750000000.0, 'aug_20': 0.0}} This is a list of 'months' passed by views.py as printed out in Django template: ['jun_20', 'jul_20', 'aug_20'] And this is the code I am using to generate a table row: {% for content in table.values %} <tr> <td>{{ content.display_id }}</td> <td>{{ content.name }}</td> {% for month in months %} <td>{{ content.month }}</td> {% endfor %} </tr> {% endfor %} And this is the output: <tr> <td>C0002</td> <td>Financial Statements</td> <td></td> <td></td> <td></td> </tr> <tr> <td>C0001</td> <td>Balance Sheet</td> <td></td> <td></td> <td></td> </tr> <tr> <td>C0006</td> <td>Non-Current Assets</td> <td></td> <td></td> <td></td> </tr> Why are the month td tags blank? If I change 'content.month' to 'content.jul_20, the tags do get the dictionary values for jul_20. I also tried converting the numbers stored … -
I used str() on string with byte literal, how do I reverse the operation?
So I had binary like the following b"My name is ...\n blah blah" then I used I used str() on it which resulted in "b'My name is ...\\n blah blah'" how can I undo this and get a variable with byte literal again? -
Vue.js instant search from API REST Framework using axios
I have a problem. I want to create instant search, without any search button, that when i'm typing e.g. more than 3 letters, my results will be instant show below. My code: <template> <div class="nav-scroller py-1 mb-2"> <div class="nav d-flex justify-content-between"> <input v-model="keyword" class="form-control" type="text" placeholder="Search" aria-label="Search"> <div v-bind:key="result.id" v-for="result in results"> <p>Results are: {{ result.title }}</p> </div> </div> </div> </template> <script> import axios from 'axios'; export default { name: 'Home', components: { }, data() { return { keyword: '', results: [], } }, methods: { getResults() { axios.get("http://127.0.0.1:8000/api/v1/books/?search="+this.keyword) .then(res => (this.results = res.data)) .catch(err => console.log(err)); } }, created() { this.getResults() } } </script> Could you help me? -
Access private data .env file in gitlab CI django
I am stuck in a issue I dont want to commit my .env file on gitlab, but during CI I need that values for database configuration like this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'postgres', 'PORT': '5432' } } while my file in actual DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": config("DB_PORT", cast=int), } } so what is possible way to assign these values to run tests.py in CI gitlab -
I need to get a blank json field on my Django and collect it as error
So far this is my code. def post(self, request): if serializer.is_valid(): if not request.data['valor_sensor']: request.data['valor_sensor'] = "ERRO" serializer = serializers.EventosSerializer(data=request.data) serializer.save() return Response(serializer.data, status.HTTP_201_CREATE I need to take the field valor_sensor, from this json, and when I collect it, IF IT IS BLANK, I need to transform it into the string "ERROR". Anyone knows how to do it? -
Conda command not found on deploying a django project to heroku
I have a django project which uses rdkit library, which is depended on conda environment. But I cannot deploy the project to heroku. When I try git push heroku master it is showing the following errors: remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python/Conda app detected remote: -----> Preparing Python/Miniconda Environment (3.8.3) remote: /tmp/codon/tmp/buildpacks/298b2b29cc393b8d85322805d763db20318c981c/bin/steps/conda_compile: line 9: conda: command not found remote: ! Push rejected, failed to compile Python/Conda app. remote: remote: ! Push failed remote: Verifying deploy... I have not created any requirements.txt file because to use rdkit I have to use rdkit channel, and I cannot find a way to specify that in requirements.txt. Instead I have used environment.yml. The environment.yml contains: name: Phytochem channels: - rdkit - defaults - conda-forge dependencies: - _libgcc_mutex=0.1 - blas=1.0 - bzip2=1.0.8 - ca-certificates=2020.6.20 - cairo=1.14.12 - certifi=2020.6.20 - dj-database-url=0.5.0 - django=3.1.2 - django-heroku=0.3.1 - fontconfig=2.13.0 - freetype=2.10.4 - glib=2.63.1 - icu=58.2 - intel-openmp=2020.2 - jpeg=9b - krb5=1.16.4 - lcms2=2.11 - ld_impl_linux-64=2.33.1 - libboost=1.73.0 - libedit=3.1.20191231 - libffi=3.2.1 - libgcc-ng=9.1.0 - libpng=1.6.37 - libpq=11.2 - libstdcxx-ng=9.1.0 - libtiff=4.1.0 - libuuid=1.0.3 - libxcb=1.14 - libxml2=2.9.10 - lz4-c=1.9.2 - mkl=2020.2 - mkl-service=2.3.0 - mkl_fft=1.2.0 - mkl_random=1.1.1 - ncurses=6.2 - numpy=1.19.2 - … -
ValueError at /cart/remove/ could not convert string to float:
This code is showing me an error. def removeFromCart(request): request.session.set_expiry(0) obj_to_remove = int(float(request.POST['obj_id'])) obj_index = request.session['cart'].index(obj_to_remove) request.seession['cart'].pop(obj_index) return redirect('cart') -
how to pass multiple admin class with iterable in django admin
from django.contrib import admin from .models import Post, Comment, DataTracking myModels = [Comment, DataTracking] @admin.register(myModels, safe=True) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'body', 'post', 'created_on', 'active') list_filter = ('active', 'created_on') search_fields = ('name', 'email', 'body') actions = ['approve_comments'] def approve_comments(self, request, queryset): queryset.update(active=True) class DataTrackingAdmin(admin.ModelAdmin): list_display = ('blogtitle','country','viewcount') list_filter = ('blogtitle','country') search_fields = ('blogtitle','country','viewcount') class PostAdmin(admin.ModelAdmin): class Media: js=("injectjs.js",) list_display = ('title', 'slug', 'status','created_on') list_filter = ("status",) search_fields = ['title', 'content'] prepopulated_fields = {'slug': ('title',)} admin.site.register(Post, PostAdmin) i am trying to this i want to register newly added DataTracking model with admin i tried passing both as seprate list admin class and itrables to admin register it gives me error -
AttributeError: module 'django.db.models' has no attribute 'ForeingKey'
Hi Guys: I´m new in Python. I'm having this error: AttributeError: module 'django.db.models' has no attribute 'ForeingKey' this is my code: from django.db import models from aplicaciones.adopcion.models import PersonaM class Vacuna(models.Model): nombre = models.CharField(max_length=50) class Mascota(models.Model): folio = models.CharField(max_length=10, primary_key=True) nombre = models.CharField(max_length=50) sexo = models.CharField(max_length=10) edad_aproximada = models.IntegerField() fecha_rescate = models.DateField() persona = models.ForeingKey(PersonaM, null=True, blank=True, on_delete=CASCADE) vacuna = models.ManyToManyField(Vacuna) Can anyone help me? Thks you all -
django heroku 1 year free vs heroku + AWS RDS 1 year?
i finich my django app and i want to deploy my app on heroku a want test it for 1 year i need free 1 year i now the limit for heroku free and its ok for me , only the limit 10000 row in database i want to avoid this limit by sit my database on AWS RDS so i can entre more than 10k row in database any one try this before and its easy or hard to conect database with heroku and the confing AWS RDS sit on setting.py or in heroku setting -
Save and duplicate an instance in django
I have to define a function in order to duplicate an instance of my class Scenario. I created an identically instance whose fields are identically except 'name' and 'id', but when I save the new instance the original is deleted. For example if I want to duplicate the scenario called s1 and to create the scenario s_dup_s1, and if I reproduce all lines of my duplicate function, then after I write s_dup_s1.save() the old instance s1 is deleted. What can I do if I want s1 and s1_sup_s1 at the same time? -
Set value for options in render_field, django-widget-tweaks
I have a render_field in my webpage which renders a "select" tag. I want to set the set the value of each option as they get rendered as indexes (1,2,3...) by default. This is my render_field. {% render_field form.type|append_attr:"oninput:this.className = ''"|append_attr:"onchange:update_make(this.options[this.selectedIndex])" class="form-control input-field" %} -
how to handle exception inside django middleware
What if middleware itself throw an error (for example some timeout error), how can I make this exception be handled by other middlewares with defined process_exception method? Do I need to throw some special django exception or return specific response? -
How to make a password access page with django model
I want to create access page for every groups in my models. this is my models.py file class TournamentGroup(models.Model): group_name = models.CharField(max_length=256, null=True) tournament_name = models.ForeignKey(Tournament, on_delete=models.SET_NULL, null=True) group_password = models.CharField(max_length=6, null=True) def __str__(self): return self.group_name class Tournament(models.Model): data = models.DateField(null=True) tournament_name = models.CharField(max_length=256, null=True) tournament_creator = models.ForeignKey(Judges, on_delete=models.SET_NULL, null=True) def __str__(self): return self.tournament_name and this is my views.py file def group_auth(request, pk): model = get_object_or_404(TournamentGroup, pk=pk) password = TournamentGroup.objects.filter(group_password=model) form = TournamentPassword() if request.method == "POST": form = TournamentPassword(request.POST) if form.is_valid(): accept = form.cleaned_data['password'] if accept == password: return redirect('ksm_app:groups') else: return HttpResponse("Hasło nieprawidłowe") return render(request, 'ksm_app2/allowed2.html', {'form': form}) I would like to create it in such a form that admin creates a tournament and assigns groups to it, each group has its own separate access code. I'm asking someone who can help me if I'm going in the right direction because now after going to the page where the user is asked for a password and after entering the page refreshes but nothing concrete happens. I would appreciate any hint -
Filter python list inside queryset
Django framework is being used. There is a model with many-to-many field. class Item(models.Model): special_category_id = models.CharField(max_length=100) categories = models.ManyToManyField(Category) and a list of category ids ids=[1, 2, 3] I need to check if at least one of categories is in ids. The problem is that special_category_id is in categories table and I need to exclude special_category_id from ids. The code bellow works, but it checks the special_category_id value too. queryset = queryset.annotate( categories_are_in_list=Case( When( Q(categories__id__in=ids), then=Value(1) ), default=Value(0), output_field=IntegerField(), ), Is it possible? -
django.db.utils.IntegrityError: Problem installing fixture UNIQUE constraint failed: users_profile.user_id
I have been trying to migrate from the default sqlite database in Django over to Postgres, and am running into problems moving the data from one to the other on my remote host. I am currently following this guide, and I have done the following: created a new postgres database, added it to my settings.py, installed psycopg2, created tables in the new database, and exported data from the old database. When I try to load the data: python manage.py loaddata alldata.json --database=pgsql I get the following error: django.db.utils.IntegrityError: Problem installing fixture '/home/amatlin/squishy/alldata.json': Could not load auth.User(pk=1): UNIQUE constraint failed: users_profile.user_id Below is the code for my file users/models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' I have also checked the contents of the users_profile table as follows: $ python manage.py dbshell SQLite version 3.31.1 2020-01-27 19:55:54 sqlite> select * from users_profile; id|image|user_id 1|profile_pics/strawberry.gif|1 Therefore there are no duplicate user_id values in the users_profile table. The postgres DB currently has the database structure of the sqlite DB because I migrated it up to the place where the sqlite DB is. … -
Serializer Multiple Models
class SupplierPO(models.Model): enterpriseId = models.IntegerField(null=True, blank=True) supplierId = models.IntegerField(null=True, blank=True) date = models.DateTimeField(null=True, blank=True) refNo = models.CharField(max_length=30,blank=True,null=True) billNo = models.CharField(max_length=30, null=True, blank=True) amount = models.FloatField(null=True, blank=True) deliveryStatus = models.CharField(max_length=20, null=True, blank=True) paymentStatus = models.CharField(max_length=20, null=True, blank=True) paymentMode = models.CharField(max_length=30,blank=True,null=True) balance = models.CharField(max_length=30,blank=True,null=True) totalQty = models.CharField(max_length=30,blank=True,null=True) noOfProducts = models.CharField(max_length=30,blank=True,null=True) deliveryDate = models.DateField(max_length=20,blank=True,null=True) receivedBy = models.CharField(max_length=20,blank=True,null=True) is_deleted = models.BooleanField(default=False) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.CharField(max_length=200, null=True, blank=True) updated_by = models.CharField(max_length=50, null=True, blank=True) class SupplierPOItems(models.Model): supplierPoId = models.ForeignKey(SupplierPO,on_delete=models.CASCADE, blank=True, null=True) productId = models.ForeignKey(ProductsEnterprise,on_delete=models.CASCADE, blank=True, null=True) warehouseId = models.ForeignKey(Warehouse, on_delete=models.CASCADE, blank=True, null=True) amount = models.CharField(max_length=30,blank=True,null=True) gstin = models.CharField(max_length=100, null=True, blank=True) mrp = models.CharField(max_length=30,blank=True,null=True) discount = models.CharField(max_length=30,blank=True,null=True) qty = models.CharField(max_length=30,blank=True,null=True) hsnNo = models.CharField(max_length=100,null=True, blank=True) gstRate = models.CharField(max_length=100, null=True, blank=True) sku = models.CharField(max_length=100, null=True, blank=True) upcNo = models.CharField(max_length=100, null=True, blank=True) is_deleted = models.BooleanField(default=False) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) created_by = models.CharField(max_length=200, null=True, blank=True) updated_by = models.CharField(max_length=50, null=True, blank=True) class SupplierPOViewSet(ModelViewSet): permission_classes = [IsAuthenticated,] queryset = SupplierPO.objects.filter(is_deleted=False).order_by('id') serializer_class = SupplierPOSerializer def list(self, request, *args, **kwargs): response = {'status_code': 200} try: queryset = SupplierPO.objects.filter(is_deleted=False).filter(enterpriseId=request.data.get('enterpriseId')).order_by('id') serializer = SupplierPOSerializer(queryset, many=True) response.update({ 'status': CommonResponse.STATUS_SUCCESS, 'message': "Supplier fetched successfully", 'data': serializer.data }) except Exception as e: response.update({ 'status_code': 204, 'message': str(e) }) … -
DateTimePicker in Django-Filters
since a few days I try to figure out how to use a DateTimePicker in my Django Project in Django 3.x. I found django-datetimepicker but its not working since in 3.0 the attribute renderer was removed and none of the solutions worked for me. My model.py class Log(models.Model): timestamp = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=30) project = models.CharField(max_length=30) status = models.PositiveIntegerField() def __str__(self): return str(self.timestamp) + " / " + self.name + " / " + str(self.status) The Table is filled from a generator and I get for each timestamp about 100 entries. my filter.py looks like this: class LogFilter(django_filters.FilterSet): project = django_filters.MultipleChoiceFilter(choices=get_choices(Log, 'project'), label='Project', field_name='project') name = django_filters.MultipleChoiceFilter(choices=get_choices(Log, 'name'), label= 'Name', field_name='name') date_range = django_filters.DateFromToRangeFilter( lookup_expr=('regex'), widget=django_filters.widgets.RangeWidget( attrs={ 'type':'date' } ), label='Date Range', field_name='timestamp' ) These filters do their job but the DateFromToRangeFilter just accepts 'date' as a datepicker object. I didn't find a solution yet to also pick a timerange. views.py def log_view(request,filterdict): obj = Log.objects.filter(**filterdict) context = { 'object' : obj, 'filter' : LogFilter(request.GET, queryset=Log.objects.all()), } return render(request, "widgets/tables/log_table.html", context) Btw: I'm using django-filters, because I want to safe the filter in the url. Thanks for helping. -
PYTHON CONVERT INT into PHONE NUMBER
I'm trying to import an excel file into my django project and create a Client object with the excel's data. this is my Client model: class Client(models.Model): client = models.CharField(max_length=255, null=False) name = models.CharField(max_length=255, blank=True, null=True) surname = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(blank=True, null=True) phone = PhoneNumberField(blank=True, null=True) i implemented this function to import the file: import phonenumbers def import_proj_excel(request): if request.method == 'POST': client_resource = ClientResource() dataset = Dataset() file = request.FILES['prog-file'] if not file.name.endswith('xlsx'): messages.info(request, 'invalid format') return render(request, 'excel.html') imported_data = dataset.load(file.read(), format='xlsx') for data in imported_data: if data[1] is None or data[2] is None or data[3] is None or data[4] is None or data[4] is None or data[5] is None: d1 = data[1] d2 = data[2] d3 = data[3] d4 = data[4] d5 = data[5] if d1 is None: d1 = "" elif d2 is None: d2 = "" elif d3 is None: d3 = "" elif d4 is None: d4 = "" elif d5 is None: d5 = str(data[5]) d5 = "" value = Cliente( data[0], d1, d2, d3, d4, d5, ) else: phone = phonemubers(data[5]) print(type(phone)) value = Client( data[0], data[1], data[2], data[3], data[4], phone, ) value.save() return render(request, 'excel.html') data[0] is the …