Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Query that filters data from 2 models having ForeignKey relation
I am trying to write a query that returns Vehicle objects. The query should filter by a particular Garage object (i.e., garage__name = ) and by a particular Category object (i.e., category__name = ), and where the Vehicle object's available field is True (available = True). These are the models: class Garage(models.Model): name = models.CharField (max_length = 30, blank=False) zip = models.IntegerField (blank=False) area = models.CharField (max_length = 30, blank=False) pic = models.ImageField (upload_to ='static/images/garages') class Vehicle(models.Model): car_no = models.CharField (max_length = 20, blank=False) photo = models.ImageField (upload_to ='static/images/vehicles') car_model = models.ForeignKey (Car_model, on_delete=models.CASCADE) garage = models.ForeignKey (Garage, on_delete=models.CASCADE) category = models.ForeignKey (Category, on_delete=models.CASCADE) available = models.BooleanField(default=True) class Category(models.Model): name = models.CharField (max_length = 15, blank=False) What I've tried in the corresponding view function is this: def carSelectView(request, type, grg): cars=Vehicle.objects.filter(category__name=type, garage__name=grg, available=True) return render(request, 'carphotoselectpage.html', {'ca':cars}) But it's returning an empty page. Before this approach, i tried to get the cars of a particular category only and it worked: def carSelectView(request, type): cars = Vehicle.objects.filter(category__name = type).filter(available=True) I can't understand where the problem lies. I want to show vehicles by 1. selecting a particular Garage, and then 2. selecting the vehicles from that Garage that matches the Category name. … -
Django Converting Queryset with Foreign Keys to JSON
I'm trying to pass JSON objects to my template. I have some complicated relationships that I can't modify. Based on OS posts I've tried different things. The ones that I think brought me close are: 1) I created a .values() queryset that looks like this and I tried to convert it to JSON: def make_querydict(): results=TodaysResults.objects.values('id','foreignModel1__name', 'foreignModel1__ForeignModel2__title') json_results=json.dumps(list(results,cls=DjangoJSONEncoder)) print (json_results) I get the following error: "TypeError: list() takes no keyword arguments" 2) I tried this as well: def serialize(): fields = ['id','foreignModel1__name','foreignModel1__ForeignModel2__title'] qs = TodaysResults.objects.all() json_data = serializers.serialize('json',qs,fields=fields) print(json_data) But when I print the json_data in only shows id and not the foreign values. 3) Based on a few answers like this(from 2012) that were along the same lines And I tried: def for_JSON_response(): response=JsonResponse(dict(results_info=list(TodaysResultslts.objects.values('id','foreignModel1__name', 'foreignModel1__ForeignModel2__title') print(response) I don't get any errors but it does not print anything.So, I'm assuming nothing happened. I've been looking around a lot and some of the responses look outdated. My attempts above are the ones that I believe came the closest to converting the valuesqueryset to json or getting the values I need into JSON. Is there a way of making a chained query like the one I have in make_querydict and convert it … -
Login Required Django Classed Based View
Totally beginner question. I have this view in my app Foo: class PaymentsView(LoginRequiredMixin, CreateView): login_url = '/login/' redirect_field_name = 'redirect_to' # -- Omitted ... I have read the django documentation but I didn't see where to put my file "login.html" and how can I set the url for that. When I run the code show the 404 error. -
PUT and Delete Request in Django rest framework
I am new to Django, I was wondering How to code PUT request and Delete method in my Django REST API Project. I have tried to follow with many tutorials, but none working with my kind of code. The code I tried looks like this def put(self, request, pk): snippet = self.get_object(pk) serializer = UserSerializers(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk): snippet = self.get_object(pk) snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT) The following is my Models.py from Django.db import models class Users(models.Model): name = models.CharField(max_length=50) profile_name = models.CharField(max_length=30) profile_picture = models.CharField(max_length=1000) phone = models.CharField(max_length=15) email = models.EmailField() def __str__(self): return self.name class UserPost(models.Model): recipe_name = models.CharField(max_length=50) recipe_image = models.CharField(max_length=1000) recipe_ingredients = models.CharField(max_length=1000) recipe_direction = models.CharField(max_length=1000) recipe_cuisine = models.CharField(max_length=30) recipe_calories = models.CharField(max_length=20) recipe_mealtype = models.CharField(max_length=30) recipe_preptime = models.CharField(max_length=20) def __str__(self): return self.recipe_name The following is my serializers.py from rest_framework import serializers from .models import Users class UserSerializers(serializers.ModelSerializer): class Meta: model = Users fields = '__all__' The following code contains my Views.py from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from .models import Users from .serializers import UserSerializers class UsersList(APIView): def get(self, request): User_details = Users.objects.all() serializer = UserSerializers(User_details, many=True) return … -
Can't syncdb because CASCADE() missing arguments
I am testing Django for the first time to create my own to do list. All has been working fine so far until I synchronise to my sqlite3 database with python manage.py syncdb I have managed to debug all the errors so far. The error I cant seem to debug is TypeError: CASCADE() missing 4 required positional arguments: 'collector', 'field', 'sub_objs', and 'using' Here is the model code: class Item(models.Model): worktasks = models.CharField(max_length=250) focus = models.CharField(max_length=250) #... todo_list = models.ForeignKey('Todo', on_delete=models.CASCADE()) def __str__(self): return self.worktasks + '-' + self.lessons I've tried removing the brackets "()" after CASCADE which resulted in the output Unknown command: 'syncdb' I am working on Pycharm - Python Version 3.7 -
DateTimeField keeps saying invalid date/time
I created a form that runs smoothly, but when I added in a DateTimeField, the form won't pass as valid anymore. I get the error that I inputted the wrong date/time; however, I have tried every date input format, and it still hasn't worked. I have a feeling the issue may lie in my form field for DateTimeField, but am unsure what the exact issue is. I would greatly appreciate any help. class Lesson(models.Model): user = models.ForeignKey(User, null=True, default=None, related_name='lessons', on_delete=models.CASCADE) lesson_instrument = models.CharField(max_length=255, choices=instrument_list, blank=True) lesson_level = models.CharField(max_length=255, choices=level_list, blank=True) lesson_length = models.CharField(max_length=255, choices=length_list, blank=True) lesson_datetime = models.DateTimeField(null=True, blank=True) lesson_weekly = models.BooleanField(default=False, blank=True) def __str__(self): return self.lessons @receiver(post_save, sender=User) def create_user_lessons(sender, instance, created, **kwargs): if created: Lesson.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_lessons(sender, instance, **kwargs): for lesson in instance.lessons.all(): lesson.save() forms.py class LessonForm(forms.ModelForm): lesson_instrument = forms.ChoiceField(choices=instrument_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_level = forms.ChoiceField(choices=level_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_length = forms.ChoiceField(choices=length_list, widget=forms.Select(attrs={'class' : 'form-control', 'required' : 'True'})) lesson_datetime = forms.DateTimeField(widget=forms.DateTimeInput(attrs={'class': 'form-control', 'type':'datetime-local'})) lesson_weekly = forms.BooleanField(required=False) class Meta: model = Lesson fields = ('lesson_instrument', 'lesson_level', 'lesson_length', 'lesson_datetime', 'lesson_weekly') views.py def new_lesson(request): if request.method == 'POST': form = LessonForm(request.POST) if form.is_valid(): lessons = form.save(commit=False) lessons.user = request.user lessons.save() messages.success(request,'Lesson successfully … -
Django Eval from Database
My group and I are trying to develop a "very-dynamic" web app with Django. We have a "configurations" template for the users where everyone can configure his/her own space. Every configuration option should be read from the DB. view: def config(request): if 'logged' not in request.session: return redirect(login) apps_list = App.objects.all() varS = varsesion(request) context = Configurations.objects.all() for row in context: row.form = eval(row.form) #Not sure at all if this is ok print (row.form) context.App = 'config' return render(request, "index.html", {'context': context, 'apps_list ': apps_list , 'varS': varS, 'context.App': context.App}) And in our DB we have the Configurations model table like this: +----+-----+-----+-----+---------+---------------+ | id |user |Title|Body |OptionBtn| form | +----+-----+-----+-----+---------+---------------+ | N |userA| X | X | X | DataConfig() | +----+-----+-----+-----+---------+---------------+ | N2 |userA| X | X | X | ColorsConfig()| +----+-----+-----+-----+---------+---------------+ | N3 |userA| X | X | X |ButtonsConfig()| +----+-----+-----+-----+---------+---------------+ And many other columns that I'll skip... Of course every Form value in the DB's form field exists in forms.py with their respective names. The problem comes when I try to iterate these forms fields in our template (every other column from the DB is displayed properly like buttons, titles, texts, etc) Here is the template … -
Django, RPi3 and RFID sensors
Can someone advice me how to do my project :) The idea is that we have a database that will store the information about a bunch of persons and it will also save when someone checks in/out. But the problem is that I don't know how to run the server and listen for RFID tags at the same time. If you have any questions, please ask me :) Thanks in advance! -
Django - Selecting from multiple tables/models
I have a model set up that is class BasePage(Page): class Meta: abstract = True class PageTypeA(BasePage): ... class PageTypeB(BasePage): ... class PageTypeC(BasePage): ... etc.. How do I create a query to list all of the pages that inherit from BasePage? -
Testing Django Signals with Mock
I am currently trying to test (pytest) my Django signals. I always receive this error here: E AssertionError: Expected call: mock(sender=<ANY>, signal=<django.dispatch.dispatcher.Signal object at 0x10a29f668>) E Actual call: mock(charge={[...]]}, order=Order: #weGnyRDPOL, sender=<class 'type'>, signal=<django.dispatch.dispatcher.Signal object at 0x10a29f668>) My signals contains a print statement: @receiver(signal=charge_succeeded) def create_influencer_transaction(sender, order, charge, **kwargs): print("TEST") When executing pytest TEST is shown, however the error above stops my tests. Do you have any idea what's wrong with my test? @contextmanager def catch_signal(signal): """Catch django signal and return the mocked call.""" handler = mock.Mock() signal.connect(handler) yield handler signal.disconnect(handler) @pytest.fixture def tester(): return StripeTester() @pytest.mark.django_db def test_should_send_signal_when_charge_succeeds(client, monkeypatch, tester): with catch_signal(charge_succeeded) as handler: # Charge normally are several lines of code that also include # client, monkeypatch, tester. However, that part works as I # receive the signal (see below). That's why I simplified it. charge(100) handler.assert_called_once_with( sender=mock.ANY, signal=charge_succeeded, ) -
Python: New Object instance on every call of function
I'm trying to update a base class with a session token and user id for long polling. Every time I call my function I create a new instance which calls a login function, that I don't want to happen. I only want to call the login() method when the value is None How do I return the instance of apiclient after the session token is set to use with the function for get_balance?? client.py from __future__ import absolute_import, unicode_literals import requests import os from matchbook import endpoints class BaseClient(object): def __init__(self, username, password=None, locale=None): self.username = username self.password = password self.locale = locale self.url_beta = 'https://beta.matchbook.com' self.urn_main = '/bpapi/rest/' self.session = requests.Session() self.session_token = None self.user_id = None def set_session_token(self, session_token, user_id): self.session_token = session_token self.user_id = user_id class APIClient(BaseClient): def __init__(self, username, password=None): super(APIClient, self).__init__(username, password) self.login = endpoints.Login(self) self.account = endpoints.Account(self) def __repr__(self): return '<APIClient [%s]>' % self.username def __str__(self): return 'APIClient' get_bal.py from client import APIClient from celery import shared_task def get_client(): apiclient = APIClient(username, password) if apiclient.session_token is None: apiclient.login() session_token = apiclient.session_token user_id = apiclient.user_id apiclient.set_session_token(session_token,user_id) if apiclient.session_token is not None: print('session token assigned',apiclient.session_token, apiclient.user_id) return apiclient @shared_task def get_balance(): apiclient = get_client() *to call … -
Get form returning None - Django 2
I'm trying to filter a view based on a input form. It means that I want to store the input variables and filter the view's model with this. There's two ways to do this: by POST or by GET. I've tried both of them, but I believe that GET method is more useful. I don't know if the problem is that I'm not using a form on forms.py or something on urls.py, views.py and the html template. Anyway. Here is my code: views.py class PareceresHistAsset(LoginRequiredMixin, ListView): login_url = 'login/' redirect_field_name = 'redirect_to' template_name = "dash_asset.html" # Obtendo o ano anterior ao vigente ano = datetime.now().year - 1 # Model Utilizado model = Pareceres queryset = Pareceres.objetos.filter(data_comite__year__gte=ano).filter(segmento='asset') # Criando os dados de context da view def get_context_data(self, **kwargs): ## Queryset do objeto queryset = self.queryset # Teste data_inicial = self.request.GET.get('data_inicial') print(data_inicial) ... urls.py from portal.views import * from django.urls import path from django.contrib.auth.views import LoginView app_name = 'portal' # urlpatterns contém a lista de roteamento URLs urlpatterns = [ # GET / ... path('asset/dash', PareceresHistAsset.as_view(), name='dash_asset'), ... ] dash_asset.html <div class="card mt-3"> <div class="card-body"> <form method="get"> <div class="row"> <!-- Data Inicial--> <div class="col-2"> <label for="data_incial">Data Inicial</label> <input id="data_incial" width="150" /> </div> … -
Django Form Returns Tuple Instead of String
I have built a web page to front my teams automation scripts, this page should return a dictionary compressed into a string from a drop down menu. Instead of a string I am getting what I think is a tuple. I need a normal string to be returned but dont know the reason for the tuple. Views: import datetime import json from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import authenticate from django.template import loader from django.urls import reverse from django.contrib import auth from home.models import ChangeLog from health.models import FirewallInfo from . import forms from . import sftpadd def ipadd_index(request): if request.user.is_staff: ipadd = forms.IPAdd() return render(request, 'ipadd/index.html', {'ipadd': ipadd}) else: return redirect('/unauthorized/') def ipadd_action(request): if request.method == 'POST': form = forms.IPAdd(request.POST) if form.is_valid(): casenum = request.POST.get('casenum') ipaddr = request.POST.get('ipaddr') objgp = request.POST.get('objgp') cidr = request.POST.get('cidr') objgp = ''.join(objgp) objgp = json.loads(objgp) asa = [] for k, v in objgp: OBJGP = k for item in v: firewall = FirewallInfo.get(fw_name=item) asa.append(firewall.fw_ip) for fw in asa: if cidr == 'HOST': sftpadd.sftpadd_host(ipaddr, fw) else: sftpadd.sftpadd_sub(ipaddr, cidr, fw) sftpadd.save(fw) dbdetails = str(ipaddr) + ' has been added to ' + str(OBJGP) dbentry = ChangeLog(user_name=request.user.username, change_date=datetime.datetime.today().strftime( '%Y-%m-%d'), change_cr='N/A', change_type='IP Add', … -
If then Python logic returns incorrect queryset Django
If no filter has been applied the page should display all users, possibly {% for user in users %} If request.POST ProfileFilter has been submitted and there are matches, the page should return the users in the queryset or {% for profile in filter.qs %} If the ProfileFilter does not return any results on request.POST, No results found should be displayed. With the current logic below the page is returning No results, try again? before anything is posted which I assume is because filter is always defined (so {% if profile in filter.qs %} is always True) so the {% for user in users %} is never running. So is it possible to define some kind of logic with {% for profile in filter.qs %} to return 1) all users if the queryset hasn't yet been posted 2) matching users if it has been posted 3) no results found if no users match? Someone please point me in the right direction! Thank you. html {% if filter %} {% for profile in filter.qs %} <h5>{{ profile.user.first_name }}</h5> <p>{{ profile.age }}</p> {% empty %} <h1>No results, try again?</h1> {% endfor %} {% else %} {% for user in users %} <h5>{{ … -
Django - order_by() char and numerical
I have to sort a list of objects containing hostnames. The hostnames are in these formats: h1, h5, h10, h12, h12-abc, h1000, x10 If i use order_by(hostname) it will order like this: h1, h10, h1000, h12, h12-abc, h5, x10 How would i achieve an ordering like this: h1, h5, h10, h12, h12-abc, h1000 The hostnames always begin with a char, then 1-4 digits and partly an extension, like for example '-abc'. I guess i have to use Substr() to extract the number and order the numbers somehow, that '10' will not be listed before '5'. With a search i found some old examples with extra() but the Django documentation says it wil be deprecated in future and 'Use this method as a last resort' https://docs.djangoproject.com/en/2.1/ref/models/querysets/#extra What is a future-proof way to do it? -
Pass Django queryset to Highcharts.js ---TypeError: values() takes no arguments (1 given)
i'm trying to pass my queryset to highcharts.js. I am able to do it using the below method: this is my view.py this is my template When I start using values() in my queryset to annotate and group columns for aggregation and append them to the data variable, it gives me this error TypeError: values() takes no arguments (1 given). views.py with values() in queryset I am fairly new to Django, so please help me. -
How to get rest of the request in serializer in python django rest framework?
I'm programming a survey application. I have model AnsewerSet that holds answers for all questions in one Survey. This is part of my models.py: class AnswerSet(models.Model): survey = models.ForeignKey('Survey', models.CASCADE, related_name='answer_sets') class Answer(models.Model): answer_set = models.ForeignKey(AnswerSet, models.CASCADE, related_name='answers') question = models.ForeignKey(Question, models.CASCASE, related_name='answers') text = models.TextField() I would like to create new AnswerSet with the following json POST: { survey_id: 1, answers: [ { text: 'I like that.' }, { text: 'Don't do that!' } ] } This is an answer for a Survey that has 2 text questions. I would like to create a serializer that is DRY - I don't want to implement everything myself in .validate() and .create() methods. I have something like this so far: class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('id', 'text', 'answer_set', 'question') read_only_fields = ('id',) class AnswerSetSerializer(serializers.ModelSerializer): answers = AnswerSerializer(many=True) class Meta: model = AnswerSet fields = ('id', 'survey', 'answers') read_only_fields = ('id',) There are multiple problems. First is that every answer requires answer_set and question (answer_set is clearly defined - I'm just creating that one, the question is defined by survey and position in the list of answers [questions are ordered]). The second problem is I'm using ListSerializer (that … -
UNIQUE constraint failed: auth_user.username error
I have a code, witch catch UNIQUE constraint error. The logic is that is create username and generate a password with sms send. @transaction.atomic def register(request): session_start(request) by_referal = request.session.get('by_referal') if request.method == "POST": user_form = UserOurRegistration(request.POST) profile_form = ProfileForm(request.POST, request.FILES) forms = [user_form, profile_form] if not by_referal: forms.append(ReferalForm(request.POST)) if all(form.is_valid() for form in forms): alphabet = ascii_letters + digits password = ''.join(choice(alphabet) for i in range(6)) #6 is length user_form.cleaned_data['password1'] = password user_form.cleaned_data['username'] = settings.MAGIC_NUMBER + USERSBD.objects.count() + 1 user_form.is_valid() user = user_form.save() Profile and USERSBD are created with signals. As I understand it's supposed I'm creating object twice, but I can't understand where. Thanks! -
Django 2.1 ProgrammingError at /admin column + _id does not exist
While trying to run my second Django 2.1 /Postgres 10 project I got stuck with the following programming error: ProgrammingError at /admin/vocs_app/subsubscriber/ column sub_subscriber.sub_prev_sst_uid_id does not exist LINE 1: ...", "sub_subscriber"."sub_next_recharge_datetime", "sub_subsc... ^ HINT: Perhaps you meant to reference the column "sub_subscriber.sub_prev_sst_uid". I can open the admin app of my application, ie. 127.0.0.1:8000/admin/vocs_app. It lists all imported models from my database; to illustrate my case I believe the following classes are sufficient: (taken from my_site/vocs_app/models.py:) from django.db import models class VneVirtualNetwork(models.Model): vne_uid = models.BigAutoField(primary_key=True) vne_nop_uid = models.ForeignKey(NopNetworkOperator, models.DO_NOTHING, db_column='vne_nop_uid') vne_name = models.CharField(max_length=50) vne_code = models.CharField(max_length=50) vne_external_id = models.CharField(max_length=100, blank=True, null=True) vne_idd_code = models.CharField(max_length=5) vne_sn_length = models.IntegerField() createdon = models.DateTimeField() createdby = models.CharField(max_length=150) createdfrom = models.CharField(max_length=150) modifiedon = models.DateTimeField() modifiedby = models.CharField(max_length=150) modifiedfrom = models.CharField(max_length=150) class Meta: managed = False db_table = 'vne_virtual_network' class SstSystemStatus(models.Model): sst_uid = models.BigAutoField(primary_key=True) sst_name = models.CharField(max_length=50) sst_description = models.CharField(max_length=100, blank=True, null=True) startdate = models.DateField(blank=True, null=True) enddate = models.DateField(blank=True, null=True) class Meta: managed = False db_table = 'sst_system_status' class SubSubscriber(models.Model): sub_uid = models.BigAutoField(primary_key=True) sub_vne_uid = models.ForeignKey('VneVirtualNetwork', models.DO_NOTHING, db_column='sub_vne_uid') sub_rpl_uid = models.ForeignKey(RplRatePlan, models.DO_NOTHING, db_column='sub_rpl_uid') sub_account_user_id = models.CharField(max_length=100, blank=True, null=True) sub_external_id = models.CharField(max_length=100) sub_hzn_uid = models.ForeignKey(HznHomezoneName, models.DO_NOTHING, db_column='sub_hzn_uid') sub_low_balance_trigger = models.BooleanField() sub_first_call_datetime = models.DateTimeField(blank=True, null=True) sub_last_enabled_datetime = models.DateTimeField(blank=True, null=True) … -
[Django][AWS S3] botocore.exceptions.clienterror an error occurred (accessdenied) when calling the PutObject operation
I am trying to connect Django project to AWS S3. settings.py contains below. AWS_ACCESS_KEY_ID = #ID AWS_SECRET_ACCESS_KEY = #Key AWS_STORAGE_BUCKET_NAME = #Bucket AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'backend/static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' IAM user is created with AmazonS3FullAccess. But when I enter python manage.py collectstatic an error occurs. You have requested to collect static files at the destination location as specified in your settings. This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 188, in handle collected = self.collect() File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 353, in copy_file self.storage.save(prefixed_path, source_file) File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/django/core/files/storage.py", line 49, in save return self._save(name, content) File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/storages/backends/s3boto3.py", line 506, in _save self._save_content(obj, content, parameters=parameters) File "/home/seokchan/server/mdocker/lib/python3.5/site-packages/storages/backends/s3boto3.py", line 521, in _save_content obj.upload_fileobj(content, … -
Encoding error: in MIME file name of attachment via AWS SES
I am trying to retrieve attachments data like file format and name of file from MIME via aws SES. Unfortunately some time file name encoding is changed, like file name is "3_amrishmishra_Entry Level Resume - 02.pdf" and in MIME it appears as '=?UTF-8?Q?amrishmishra=5FEntry_Level_Resume_=E2=80=93_02=2Epdf?=', any way to get exact file name? -
2 SQL Server Databases in Django Project
I have a problem loading data in database1 (default). You see, the system only has to load data that is in the database2 (source). the system works in the machine of my confessor but it has two different ports loaded and uses docker, I have the SQL server installed. The system starts, the problem is that when I want to load a data in the database1 it tells me that this data does not exist in the database2, then it does not. Now, if I try to load data that is not in the database2 if it loads correctly. I searched how to change the ports of the SQL Server but I did not get it. Can anyone help me? DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'database1', 'HOST': 'name\\name', 'PORT': '', 'USER': 'user1', 'PASSWORD': 'password1', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } }, 'source': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'database2', 'HOST': 'name\\name', 'PORT': '', 'USER': 'user2', 'PASSWORD': 'password2', 'OPTIONS': { 'driver': 'ODBC Driver 13 for SQL Server', } } -
Testing Django signals
I am currently trying to test my Django signals and wrote the following test in pytest. @pytest.fixture def tester(): return StripeTester() @pytest.mark.django_db def test_should_send_signal_when_charge_succeeds(client, monkeypatch, tester): signal_was_called = False def handler(sender, order, charge, **kwargs): signal_was_called = True charge_succeeded.connect(handler) # Charge normally are several lines of code that also include # client, monkeypatch, tester. However, that part works as I # receive the signal (see below). That's why I simplified it. charge(100) assert signal_was_called == True charge_succeeded.disconnect(handler) In my signal I added a print statement: @receiver(signal=charge_succeeded) def create_transaction(sender, **kwargs): print("TEST") I can see TEST when running pytest so the signal seems to go through. However I always get this error message when running pytest: assert signal_was_called == True assert False == True Do you have any idea why it's not True, despite the signal is working? -
HTML Page not completely loading
I am very new to web development (but not coding), so please take this with a grain of salt. I used Django to start a project, and am using some free Boostrap themes which I found online. On my home page, I learned how to link to another page by adding URLS and basic View functions in urls.py and views.py respectively. The link "somewhat" works, however it seems to only load the very basics of html (No special text or colours as I have designed using the Bootstrap theme). Here is the homepage where the link is found. HomePage (Where you click the link) This is what the page loads when clicked upon. Not_fully_loaded_pic Here is what the HTML Page should look like (When I open it through the file navigator) Fully_loaded_page . . . . Here is my urls.py in the homepage templates folder: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.HomeView.as_view(), name='home'), url(r'^api/data/$', get_data, name='api-data'), url(r'^about/$', views.AboutPageView.as_view(), name='about'), url(r'^test_page/$', views.test_page), url(r'^transactions/', include('transactions.urls')) ] This is the views.py inside the transaction folder (where index.html is the page I attempt to load): class TransactionView(TemplateView): template_name = 'transactions_page/index.html' def transaction_page(request): return render(request, 'transactions_page/index.html') Finally, my urls.py inside the transaction template folder: urlpatterns … -
Django admin panel renders "s" after table/model names
I have no idea what's going on, here's a screenshot