Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Facing issue to connect to SQLLITE table using raw sql
I'm trying to connect to SQLite table using rawsql querry but unsuccessfully . Here is my model : class CsqAgentReport(models.Model): nodeid_sessionid_sequenceno = models.TextField(db_column='NodeID-SessionID-SequenceNo', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. callstarttime = models.TextField(db_column='CallStartTime', blank=True, null=True) # Field name made lowercase. callendtime = models.TextField(db_column='CallEndTime', blank=True, null=True) # Field name made lowercase. contactdisposition = models.IntegerField(db_column='ContactDisposition', blank=True, null=True) # Field name made lowercase. originatordn_callingnumber_field = models.IntegerField(db_column='OriginatorDN(CallingNumber)', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. Field renamed because it ended with '_'. destinationdn = models.IntegerField(db_column='DestinationDN', blank=True, null=True) # Field name made lowercase. callednumber = models.IntegerField(db_column='CalledNumber', blank=True, null=True) # Field name made lowercase. pivotoriginatordn = models.TextField(db_column='PivotOriginatorDN', blank=True, null=True) # Field name made lowercase. pivotcallednumber = models.TextField(db_column='PivotCalledNumber', blank=True, null=True) # Field name made lowercase. csqnames = models.TextField(db_column='CSQNames', blank=True, null=True) # Field name made lowercase. queuetime = models.TextField(db_column='QueueTime', blank=True, null=True) # Field name made lowercase. agentname = models.TextField(db_column='AgentName', blank=True, null=True) # Field name made lowercase. ringtime = models.TextField(db_column='RingTime', blank=True, null=True) # Field name made lowercase. talktime = models.TextField(db_column='TalkTime', blank=True, null=True) # Field name made lowercase. worktime = models.TextField(db_column='WorkTime', blank=True, null=True) # Field name made lowercase. nomcsq = models.TextField(db_column='NomCSQ', blank=True, null=True) # Field name made lowercase. idunique … -
Django, download button instead of downloading image is redirecting to source url
I'm trying to download an image from an AWS storage on click. But when I use the image URL as my href it just redirects to that URL instead of downloading. Of course, I am using the download attribute. I am using Django Template and AWS S3 for storage. Here is my code:- index.html <a download href="{{ portfolio.file.url }}" title="Download" target="_blank"> <i class='bx bxs-download pl-2'></i> </a> views.py def index(request): portfolio = Image.objects.all() context = {"portfolio": portfolio} return render(request, "index.html", context) -
How to access the form variable in FormView
I can access the "form" variable in function based view like: if form.is_valid(): async_mailer.delay(from_address, **form**, None) But When I converted this function based view to class based view and tried to access the variable then I failed. Error is :EncodeError: Can't pickle <type 'function'>: attribute lookup builtin.function failed What I am tring: class MyForm(forms.form): name = form.... reply_to = forms... def save(self,*args,**kwargs): async_mailer.delay(from_address, self , None) I also tried self.form,self.instance but this does not works. -
Does django skip remaining items from the list sent to bulk_update if number of items cross the batch_size?
I was running a data import program in a table and the data I had was nearly one million. So, I went with Django bulk_create and bulk_udpate. I've put a batch_size=500 in the update. Now, what my concern is that, if the list of objects contains more data than the batch_size, does Django throw them away or iteratively insert in batches to the database? I saw some of the data are updated in the table but some are not. -
Losing data from basetemplateview
I have base template view with some data from models which is stored in context. So this template is being used everywhere, when we do post request in from other view I am not able to see the data that is being fetched from models in basetemplateview get_context_data(). class BaseTemplateView(TemplateView): template_name = 'base.html' def get_context_data(self, **kwargs): context['info'] = models.Info.objects.get(id=1) return context class TesView(BaseTemplateView): template_name = 'test.html' form = forms.TestForm def post(self, request, *args, **kwargs): try: c={} c.update(csrf(request)) form = forms.TestForm(request.POST) if not form.is_valid(): variables = {'form': form } messages.error(request, 'Invalid data in form') return render(request, self.template_name, variables ) else: from_date = str(form.cleaned_data['from_date']) to_date = str(form.cleaned_data['to_date']) data = models.Logs.objects.all() if not data: variables = {'form': form } messages.info(request, 'No data found') return render(request, self.template_name, variables) else: data_render = {'data':data, 'title':'Logs', 'form': form} return render(request,self.template_name,data_render) except Exception, exp: logger.error("Logs failed") logger.exception(exp) def get_context_data(self, **kwargs): context = super(TestView, self).get_context_data(**kwargs) context['title'] = 'Logs' context['data'] = models.SystemLogs.objects.filter(Q(ts__range=(from_date,to_date))) context['form'] = self.form return context I am getting data of basetemplateview in testview get request, but for post request i am not able to get data of basetemplateview. -
Check if event target is a file or a value
So basically what my question originates from is me trying to upload an image using a class based react component but I'm having trouble because image is event.target.files whereas other fields I have such as name and title are event.target.values. So far my state and setState look like this. state = { name: '', title: '', caption: '', image: '' } onChange = e => { // I think conditional will go here this.setState({ [e.target.name]: e.target.value }) } How could I create a conditional which checks whether the event.target is a value or a file? Another side question. Since the image is a file and not a value is my state set up correctly? -
Pleae help me solve this issue I deployed my app in heroku
This is the link to the error https://dpaste.com/EC8JPPZTD#wrap -
Role "your_db_user" does not exist
I try to connect my django application and postgres. There is my settings.py file: ... DATABASES = { "default": { "ENGINE": os.environ.get("DB_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("DB_NAME", os.path.join(BASE_DIR, "db.sqlite3")), "USER": os.environ.get("DB_USER", "user"), "PASSWORD": os.environ.get("DB_PASSWORD", "your_db_password"), "HOST": os.environ.get("DB_HOST", "your_db_name"), "PORT": os.environ.get("DB_PORT", "5432"), } } ... There is my envs: DB_ENGINE=django.db.backends.postgresql DB_USER=your_db_user DB_PASSWORD=your_db_password DB_NAME=your_db_name DB_HOST=0.0.0.0 DB_PORT=5432 There is my docker image: db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ ports: - 5432:5432 env_file: - envs/.env.local environment: - POSTGRES_USER=your_db_user - POSTGRES_PASSWORD=your_db_password - POSTGRES_DB=your_db_name Django application logs: django.db.utils.OperationalError: FATAL: password authentication failed for user "your_db_user" pg logs: Role "your_db_user" does not exist. Which problem can be? I can't suppose any problem with it -
Image from ModelForm not being saved
I have a Pgae model in wagtail that is holding an ImageField: from django.conf import settings from wagtail.users.models import upload_avatar_to from django.utils.translation import gettext_lazy as _ class ProfilePage(Page): avatar = models.ImageField( # Also updated from user.wagtail_userprofile.avatar verbose_name=_("profile picture"), upload_to=upload_avatar_to, blank=True, ) intro = RichTextField( blank=True, null=True, verbose_name=_("Personal introduction"), help_text=_("maximum number of characters: 80 characters"), max_length=80, ) school = models.CharField( verbose_name=_("School name"), max_length=100, blank=True, null=True ) school_details = models.CharField( blank=True, null=True, verbose_name=_("School details"), help_text=_("example: Faculty of Medicine"), max_length=100, ) location = models.CharField( verbose_name=_("Location"), max_length=50, blank=True, null=True, help_text=_("example: Osaka"), ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, verbose_name=_("User") ) I needed to create a modelform as I am rendering a customized template to set up profile after signing up: from django import forms from django.forms import ModelForm class ProfilePageDetailsForm(ModelForm): intro = forms.CharField( required=False, widget=forms.Textarea, label=_("Personal introduction"), help_text=_("maximum number of characters: 80 characters"), max_length=80, ) class Meta: model = ProfilePage fields = [ "avatar", "title", "school", "location", "intro", ] my view.py: def profile_details(request: HttpRequest, pk: int = None) -> HttpResponse: user = cast("User", request.user) profile = ProfilePage.objects.get(pk=pk) form = ProfilePageDetailsForm(instance=profile) if request.method == "POST": form = ProfilePageDetailsForm(request.POST, instance=profile) if form.is_valid(): form.save() return redirect("wagtailadmin_home") context = { "user": user, "form": form, } return render(request, "account/profile_details.html", context) … -
System check identified some issues:
ERRORS: <class 'shop.admin.ProductAdmin'>: (admin.E122) The value of 'list_editable[0]' refers to 'price', which is not contained in 'list_display'. <class 'shop.admin.ProductAdmin'>: (admin.E122) The value of 'list_editable[1]' refers to 'available', which is not contained in 'list_display'. System check identified 2 issues (0 silenced). -
Is there any method to join to querysets using django
I have two models defined something like class Temperature(models.Model): timestamp=models.DateTimeField() temperature=models.FloatField() class WaterLevel(models.Model): timestamp=models.DateTimeField() data=models.JSONField() I have a database function defined as class Bucket(models.Transform): template = "EXTRACT(EPOCH FROM %(expressions)s)::bigint/%(bucket_size)d" allow_distinct = True def __init__(self, expression, bucket_size=5,**extra): if bucket_size<0: raise ValueError('Bucket size must be a positive integer') super().__init__(expression, bucket_size=int(bucket_size), **extra) I then have a function that does something like def get_buckets(bucket_size): temperature_readings = ( Temperature.objects.values(bucket=Bucket("timestamp", bucket_size=15)) .annotate(temperatures=Count("timestamp")) .values("bucket", "temperatures") ) water_levels = ( WaterLevel.objects.values(bucket=Bucket("timestamp", bucket_size=15)) .annotate(levels=Count("timestamp")) .values("bucket", "levels") ) # This doesn't work, because there is no join method on a query_set return temperature_readings.join( water_levels, on=Q(tick=OuterRef("tick")) ).values_list("tick", "temperatures", "water_levels") Obviously the join method used doesn't exist and as such its signature is entirely constructed. I would expect this to return something like [ ( 1234, 10, 15), ( 1235, None, 15), ( 1236, 10, None), ( 1239, 1, 12), ... ] is there any method built into Django to accomplish this? -
request.POST not reading form data in django
I have my views file: from django.shortcuts import render from .models import Note # Create your views here. def index(request): return render(request, "index.html", {}) def write(request): notes = Note.objects return render(request, "write.html", {}) def create(request): if request.POST: body = request.POST['note'] title = request.POST['title'] print(f'title = { title }\nbody = { body }' and my html code: <h1>CREATE A NOTE</h1> <form action="{% url 'notes:create' %}" method="post"> {% csrf_token %} <label for="title">Title</label> <input type="text" name="title"><br> <label for="note">Note</label> <input type="text" name="note"><br> <input type="submit" value="Submit"> </form> Whenever I submit this form and try to access either the title or note values I get a MultiValueDictKeyError -
how to store excel file into django models genrating from pandas operation
I want to store an excel file created from pandas dataframe into django models but when I save it an entity create into models but no file exist Models.py class TaskResult(models.Model): result_file = models.FileField(blank=False, null=False) def __str__(self): return self.result_file.name views.py def handle_uploaded_file(request): file_obj = excelFile.objects.all().order_by('-id')[0] excel = file_obj.file.read() data_1 = pd.read_excel(excel) data_1 = data_1.dropna() Acceptence = data_1['Accepted Compound ID'] index_PC = Acceptence.str.endswith('PC') index_LPC = Acceptence.str.endswith('LPC') index_plasmalogen = Acceptence.str.endswith('plasmalogen') data_LPC = data_1.loc[index_LPC] task_obj = taskResult() task_obj.result_file = data_LPC.to_excel('data_LPC.xlsx') task_obj.save() -
how to generate token in login api view for authentication in django?
This is my user login view. I want to know the command that will automatically generate the token for that user after logging in, so that I can logout that user deleting that token later. class LoginUserView(GenericAPIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data=serializer.data return response.Response(new_data, status=status.HTTP_200_OK) return response.Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) In my settings. INSTALLED_APPS = [ 'rest_framework', 'rest_framework.authtoken'] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } This is my serializers: class UserLoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(label='Email Address') class Meta: model = User fields = [ 'email', 'password', ] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): user_obj = None email = data.get("email", None) password = data.get("password") if not email: raise serializers.ValidationError("Email is required for login") user = User.objects.filter(Q(email=email)).distinct() if user.exists() and user.count() ==1: user_obj = user.first() else: raise serializers.ValidationError("This email is not valid/already exists") if user_obj: if not user_obj.check_password(password): raise serializers.ValidationError("Incorrect password") return data -
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine in django
I am trying to implement email in an django application using sendgrid. Whenever I try to send email I run into the below exception. winerror 10053 an established connection was aborted by the software in your host machine I am using windows 10, python 3.7.6 and django 3.0.8. -
Can't run django project in docker
when im running docker it stucks on this part: Recreating payments_app_1 ... Recreating payments_app_1 ... done Attaching to payments_app_1 app_1 | Watching for file changes with StatReloader Dockerfile FROM python:3.6 ENV PATH="/scripts:${PATH}" COPY ./requirements.txt /requirements.txt RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers RUN pip install -r /requirements.txt RUN apk del .tmp RUN mkdir /app COPY ./app /app WORKDIR /app COPY ./scripts /scripts RUN chmod +x /scripts/* RUN mkdir -p /vol/web/media RUN mkdir -p /vol/web/static RUN adduser -D user RUN chown -R user:user /vol RUN chmod -R 755 /vol/web USER user CMD ["python","manage.py","runserver"] docker-compose version: '3.3' services: app: build: context: . ports: - "8000:8000" volumes: - ./app:/app command: sh -c "python manage.py runserver 0.0.0.0:8000" environment: - DEBUG=1 requirements.txt Django==3.1.2 -
Django Dictionary data in Dictionary how to get in single dictionary
I am new to this django and i come to a solution to this problem please help This is how my data is coming { "total_revenue": { "plan_id__plan_price__sum": 363 }, "thirty_days_revenue": { "plan_id__plan_price__sum": 363 }, "last_year_sale": { "plan_id__plan_price__sum": 363 } } I want my data to be like this { "total_revenue" : 363, "thirty_days_revenue": 363, "last_year_sale": 363 } My serializer is this: @staticmethod def get_total_revenue(self): total_revenue = self.aggregate(Sum('plan_id__plan_price')) return total_revenue @staticmethod def get_thirty_days_revenue(self): today_date = datetime.datetime.today() last_month = datetime.timedelta(days=30) date = (today_date - last_month) revenue = self.filter(created_on__range=(date, today_date)).aggregate(Sum('plan_id__plan_price')) return revenue @staticmethod def get_last_year_sale(self): today_date = datetime.datetime.today() last_month = datetime.timedelta(days=365) date = (today_date - last_month) revenue = self.filter(created_on__range=(date, today_date)).aggregate(Sum('plan_id__plan_price')) return revenue -
Python3 Django REST Framework, what's the best way to run a task in 2020?
Lately I have been building a REST API from the ground up. I eventually want to add endpoints that will trigger a task to run. So I have endpoints that are resources (ie 0.0.0.0/todos/1) and allow CRUD operations, and eventually endpoints that will be hit to execute tasks (ie 0.0.0.0/run_task_for_todo) I have looked into celery and redis and it looks promising. But is there a better way to do this on AWS? I know the basics of AWS EC2, but that is only scratching the surface... I was thinking about using AWS Lambda to serve the REST API, and possibly AWS SQS for the task queue... then have (maybe?) an ec2 instance that constantly polls the AWS SQS, and based on the incoming events execute the task? This might not even be the correct place to post this question but I figured I'd give it a shot here first. Thanks to all of those who reply in advance! -
Why the Models not showing up in django website
I am making a news website and i have made a model of an image, title, description,url(for clickable image), but the final output is not just showing up and there is no error . Please also look into image links I have attached The output Screenshot and The admin Page screenshot The output AdminPage Screenshot Main Code <div class="col-lg-9 stretch-card grid-margin"> <div class="card"> <div class="card-body"> {% for Flash in flashes %} <div class="row"> <div class="col-sm-4 grid-margin"> <div class="position-relative"> <div class="rotate-img"> {% if Flash.url %} <a href="{{ Flash.url }}"> <img src="{{ project.image.url }}" alt="thumb" class="img-fluid" /> </a> {% else %} <img src="{{ project.image.url }}" alt="thumb" class="img-fluid" /> {% endif %} </div> <div class="badge-positioned"> <span class="badge badge-danger font-weight-bold" >Flash news</span > </div> </div> </div> <div class="col-sm-8 grid-margin"> <h2 class="mb-2 font-weight-600"> {{ Flash.title }} </h2> <div class="fs-13 mb-2"> <span class="mr-2">Photo </span>10 Minutes ago </div> <p class="mb-0"> {{ Flash.description }} </p> </div> </div> {% endfor %} {% endblock %} </div> </div> </div> Views.py from django.shortcuts import render from .models import AllProject from .models import Flash def techhome(request): allprojects = AllProject.objects.all() return render(request, 'techworld/techhome.html', {'allprojects':allprojects}) def Flashnews(request): flashes = Flash.objects.all() return render(request, 'techworld/techhome1.html', {'flashes':flashes}) Models.py from django.db import models class AllProject(models.Model): title = models.CharField(max_length=100) description … -
I just connect my mongodb with django but It did't work
I am trying to connect mongodb with django, everything looks correct but it did not create a default table for me. when I makemigrations and migrate I got this. enter image description here but It did not create anything to my database, How can't I check the connection or what I was wrong :( -
how to access google spreadsheet json file from s3 while using aws lambda with django
I am using django and deployed my application on aws_lambda. Everything worked fine until i wanted to save the content of the database in a google spreadsheet The problem is how to access/get the json.file (that would normally be located in the same folder as where i am using it) now that i am aws_lambda in production views.py scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] credentials = ServiceAccountCredentials.from_json_keyfile_name("secret-json-file.json", scope) gc = gspread.authorize(credentials) open_google_spreadsheet = gc.open('data').sheet1 but since i am using aws_lambda and i stored that json on the main folder of aws s3 I am trying something like this s3_client = boto3.client("s3") response = s3_client.get_object(Bucket=aws_bucket, Key="secret-json-file.json") data = response["Body"].read() # Google spreadsheet scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] credentials = ServiceAccountCredentials.from_json_keyfile_name(data, scope) I also tried this approach: AWS_ID = aws_access_key_id AWS_KEY = aws_secret_access_key AWS_S3_BUCKET = secrets.aws_bucket session = boto3.session.Session(aws_access_key_id=AWS_ID, aws_secret_access_key=AWS_KEY) s3 = session.resource("s3") my_s3_bucket = s3.Bucket(AWS_S3_BUCKET) current_s3_file = [] for s3_file in my_s3_bucket.objects.all(): if s3_file.key == "secret-json-file.json": current_s3_file.append(s3_file) # Google spreadsheet scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] credentials = ServiceAccountCredentials.from_json_keyfile_name(current_s3_file, scope) Unfortunately both approaches are not successful. Any help would be much appreciated -
Get form value on Inline
I'm working with the Django administrator, I have a SampleAdmin with an Inline Order inside, in which I need to filter records in the latter depending on what is selected in the SampleAdmin (that is, a nested field or nested selects) So far I have this in admin.py: class SampleAdmin(admin.ModelAdmin): list_display = ('number', 'sample', 'date', 'acept') fields = (('matrix', 'type_sample'),('sample')) inlines = (OrderInline,) ------------------------------------------------------------------------------------------------ class OrderInline(admin.TabularInline): model = Result fields = ('assay',) def formfield_for_foreignkey(self, db_field, request=None, **kwargs): if db_field.name == "assay": kwargs["queryset"] = Assay.objects.filter(matrix_id=3) return super(OrderInline, self).formfield_for_foreignkey(db_field, request, **kwargs) Where the number 3 is found, I would like to place the ID value of the matrix field of SampleAdmin. From already thank you very much, greetings -
Django: Including a view in another view and running the subviews GET method
If I have a view (FruitObservations) that is rendering a template, and I'm trying to access another view (UpdateFruitObservations) via include, is there a way I can provoke the included view to do more than show its templated HTML, and actually run its GET method? It's showing the included HTML just fine, but refuses to render an included formset through the running of the GET method, it seems. I just get the rendered written HTML (no form) but the id renders in the HTML text. {% include "./update_fruit_observation.html" with fruit_id=fruit.id %} I should also mention that I'm rendering the subview's HTML as a bootstrap 4 modal, if that matters, and opening the modal via jQuery. Also, there is no network request running to the 'update-fruit-observation' URL -
Firebase Admin SDK vs fcm-django
I'm developing mobile backend using Django. I need to send remote push notifications to iOS device using Firebase Cloud Messaging. It seems I have two options. 1. Use Firebase Admin SDK, 2. fcm-django. There are little info about those on web so I'm wondering which one is better. What are pros and cons of using those frameworks and which should I use? -
Writable nested serializers with inherited django models
I'm struggling to update records with the writeable nested serializers I've created. There are many Listing categories for a classifieds app I'm creating that each have a few unique attributes, but they also share many attributes. I have a handful of django models that inherit from a parent Listing model, and one of these models, Battery, contains some nested data. So far I've been able to create Battery records but keep getting AttributeErrors when I try to update them. I've tried to include only the relevant code. Here are my views: # views.py class ListingCreateView(CreateAPIView): queryset = Listing.objects.all() def get_serializer_class(self): category = self.request.data['category'] if category == 1: return PercussionSerializer elif category == 6: return BatterySerializer return ListingSerializer class ListingUpdateView(UpdateAPIView): queryset = Listing.objects.all() def get_serializer_class(self): category = self.request.data['category'] if category == 1: return PercussionSerializer elif category == 6: return BatterySerializer return ListingSerializer here are my models: # models.py ## Parent model class Listing(models.Model): title = models.CharField(max_length=100) description = models.TextField(blank=True) price = models.DecimalField(max_digits=9, decimal_places=2, blank=True, null=True, default=0.00) ## One of the child models class Battery(Listing): model_name = models.TextField(blank=True, null=True, default="") color = models.ForeignKey(Color, on_delete=models.CASCADE, blank=True, null=True) manufacture_year = models.IntegerField(null=True) ## Model for the nested data in Battery model class Drum(models.Model): drum_type = …